For years I have been using the following pattern to remove duplicates from an object of the C++ std::vector
type:
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.
The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList: List<String> al = new ArrayList<>(); // add elements to al, including duplicates Set<String> hs = new HashSet<>(); hs. addAll(al); al.
I don't know about performance, but what about converting the QList
into a 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())
If you are creating this list:
Then avoiding duplicates may 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 >)...
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 == operator like the one above can allow QList to evaluate the contains() method against a custom datatype
QList<SoftDrink> uniquePurchaseHistory;
SoftDrink newPurchase;
if(!uniquePurchaseHistory.contains(newPurchase)){
uniquePurchaseHistory.append(newPurchase);
}
Without Warranty:
With QVector it seems to work ...
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:
QVector<QString> vect;
vect << "red" << "green" << "blue" << "black";
QList<QString> list = vect.toList();
// list: ["red", "green", "blue", "black"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With