C++ 从 QList 中删除重复项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3733837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing duplicates from a QList
提问by Vlado Klimovsky
For years I have been using the following pattern to remove duplicates from an object of the C++ std::vector
type:
多年来,我一直使用以下模式从 C++std::vector
类型的对象中删除重复项:
std::vector<int> cont;
std::sort(cont.begin(), cont.end());
cont.erase(std::unique(cont.begin(), cont.end()), cont.end());
Now I am wondering if the same paradigm is the one to be used with the Qt QList<>
class, or if there is a more elegant way to do it.
现在我想知道 QtQList<>
类是否使用相同的范式,或者是否有更优雅的方法来做到这一点。
采纳答案by Jér?me
I don't know about performance, but what about converting the QList
into a QSet
?
我不知道性能,但是如何将 转换QList
为QSet
?
QList<int> myQList;
//...
QSet<int> = QSet::fromList(myQList);
// or
QSet<int> = myQList.toSet();
(and maybe convert it back to a QList
if needed with QList::fromSet())
(QList
如果需要,可以使用QList::fromSet()将其转换回 a )
回答by SketchBookGames
If you are creating this list:
如果您要创建此列表:
Then avoiding duplicatesmay be a viable alternative to removing duplicates.
那么避免重复可能是删除重复的可行替代方案。
QList<int> cont;
int incomingValue;
if(!cont.contains(incomingValue))
{
cont.append(incomingValue);
}
Additionally, Since this is a question about QList< > (and not only QList< int >)...
此外,由于这是一个关于 QList<>(而不仅仅是 QList<int>)的问题......
Some may be using a custom class, and like to avoid duplicates.
有些人可能正在使用自定义类,并希望避免重复。
class SoftDrink
{
public:
int oz
QString flavor
bool operator==(const Beverage &other) const{
uint hash = qHash(flavor) ^ oz;
uint otherHash = qHash(other.flavor) ^ other.oz;
return hash == otherHash;
}
}
an == operatorlike the one above can allow QList to evaluate the contains() method against a custom datatype
一个==操作者像上面的可允许的QList评估针对自定义数据类型的含有()方法
QList<SoftDrink> uniquePurchaseHistory;
SoftDrink newPurchase;
if(!uniquePurchaseHistory.contains(newPurchase)){
uniquePurchaseHistory.append(newPurchase);
}
回答by havore
Without Warranty:
无保修:
With QVector it seems to work ...
使用 QVector 它似乎工作......
QVector<int> v;
std::sort( v.begin(), v.end() );
v.erase( std::unique(v.begin(), v.end() ), v.end() );//remove duplicates
From Vector back to list:
从 Vector 回到列表:
QVector<QString> vect;
vect << "red" << "green" << "blue" << "black";
QList<QString> list = vect.toList();
// list: ["red", "green", "blue", "black"]