加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 从QList中删除重复的对象

发布时间:2020-12-16 09:41:48 所属栏目:百科 来源:网络整理
导读:我有一个QList MyData,其中MyData有2个成员,int id(唯一)和QString名称.我想根据名称删除所有重复的条目,并且该条目必须是具有相同名称的其他对象之间的最高ID.有关如何以最快的方式做到这一点的任何建议?性能是一个非常重要的因素. 我的一些想法在Google-e
我有一个QList< MyData>,其中MyData有2个成员,int id(唯一)和QString名称.我想根据名称删除所有重复的条目,并且该条目必须是具有相同名称的其他对象之间的最高ID.有关如何以最快的方式做到这一点的任何建议?性能是一个非常重要的因素.

我的一些想法在Google-ed之后的一整天:

> qStableSort()它基于id(降序),然后遍历QList,然后对于每个条目,当新QList上不存在名称时,将条目复制到另一个新QList
>使用QList :: toSet(删除所有重复的条目),并提供operator ==()和基于名称的qHash()实现,但唯一条目可能没有最高的id
>使用std :: list :: unique,但我不确定它是如何工作的.

解决方法

std::list::unique可以将具有以下属性的函数作为参数:

Binary predicate that,taking two values of the same type than those
contained in the list,returns true to remove the element passed as
first argument from the container,and false otherwise.
This shall be a function pointer or a function object.

所以在你的情况下你可以使用以下功能:

bool shouldRemove(MyData first,MyData second)
{
    // remove only if they have the same name and the first id
    // is smaller than the second one 
    return ( first.name == second.name && 
             first.id <= second.id ); 
}

简单地称之为,

std::list<MyData> myList = qlist.toStdList();
myList.unique(shouldRemove)

请注意,您需要先对std :: list进行排序

编辑

看来你可以在Qt容器中使用std :: unique(如果Qt是用STL支持构建的).所以在这种情况下,您可以执行以下操作:

// lessThan is a function that sorts first by name and then by id
qSort(qList.begin(),qList.end(),lessThan );
QList<MyData>::iterator it = std::unique (qList.begin(),shouldRemove);
qList.erase(it,qList.end());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读