我有一个QList<MyData>,MyData有2个成员,int id(独特)和QString name.我想删除所有重复的条目name,并且该条目必须在id具有相同的其他对象之间最高name.有关如何以最快的方式做到这一点的任何建议?性能是一个非常重要的因素.
我的一些想法在Google-ed之后的一整天:
qStableSort()它基于id(降序),然后循环遍历QList,然后对于每个条目,将条目复制到另一个新的QList时候新的name不存在QListQList::toSet(删除所有重复的条目),并提供operator ==()和基于qHash()的实现name,但唯一条目可能没有最高的idstd::list::unique,但我不确定它是如何工作的.std::list::unique 可以将具有以下属性的函数作为参数:
二进制谓词,取两个与列表中包含的值相同的值,返回true以从容器中删除作为第一个参数传递的元素,否则返回false.这应该是一个函数指针或一个函数对象.
所以在你的情况下你可以使用以下功能:
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 );
}
Run Code Online (Sandbox Code Playgroud)
简单地称之为,
std::list<MyData> myList = qlist.toStdList();
myList.unique(shouldRemove)
Run Code Online (Sandbox Code Playgroud)
请注意,您需要先排序 std::list
编辑
看来,你可以用std::unique与Qt containers(如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(), qList.end(), shouldRemove);
qList.erase(it, qList.end());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5766 次 |
| 最近记录: |