c – 从QList中删除重复的对象
我有一个QList< MyData>,其中MyData有2个成员,int id(唯一)和QString名称.我想根据名称删除所有重复的条目,并且该条目必须是具有相同名称的其他对象之间的最高ID.有关如何以最快的方式做到这一点的任何建议?性能是一个非常重要的因素.
我的一些想法在Google-ed之后的一整天: > qStableSort()它基于id(降序),然后遍历QList,然后对于每个条目,当新QList上不存在名称时,将条目复制到另一个新QList 解决方法std::list::unique 可以将具有以下属性的函数作为参数:
所以在你的情况下你可以使用以下功能: 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()); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |