多年来,我一直使用以下模式从C++ std::vector类型的对象中删除重复项:
std::vector<int> cont;
std::sort(cont.begin(), cont.end());
cont.erase(std::unique(cont.begin(), cont.end()), cont.end());
Run Code Online (Sandbox Code Playgroud)
现在我想知道相同的范例是否与Qt QList<>类一起使用,或者是否有更优雅的方式来实现它.
Jér*_*ôme 15
我不知道性能,但是将其QList转换为QSet?
QList<int> myQList;
//...
QSet<int> = QSet::fromList(myQList);
// or
QSet<int> = myQList.toSet();
Run Code Online (Sandbox Code Playgroud)
(QList如果需要,可以将其转换回QList :: fromSet())
如果您要创建此列表:
那么避免重复可能是删除重复的可行替代方案。
QList<int> cont;
int incomingValue;
if(!cont.contains(incomingValue))
{
cont.append(incomingValue);
}
Run Code Online (Sandbox Code Playgroud)
此外,由于这是一个关于 QList<>(而不仅仅是 QList<int>)的问题......
有些人可能正在使用自定义类,并希望避免重复。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
一个==操作者像上面的可允许的QList评估针对自定义数据类型的含有()方法
QList<SoftDrink> uniquePurchaseHistory;
SoftDrink newPurchase;
if(!uniquePurchaseHistory.contains(newPurchase)){
uniquePurchaseHistory.append(newPurchase);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18791 次 |
| 最近记录: |