Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates from a QList

Tags:

c++

qt

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.

like image 719
Vlado Klimovský Avatar asked Sep 17 '10 08:09

Vlado Klimovský


People also ask

How do I remove duplicates from a list hash Set?

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.


3 Answers

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())

like image 112
Jérôme Avatar answered Oct 04 '22 21:10

Jérôme


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);
}
like image 34
SketchBookGames Avatar answered Oct 04 '22 22:10

SketchBookGames


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"]
like image 39
havore Avatar answered Oct 04 '22 20:10

havore