How to remove a repeating element in a vector, effectively

I have

 vector<string> data ; // I hold some usernames in it

In this vector, I have repeating element (s), so I want to delete this / these elements. Is there any algorithm or library function to remove duplicate elements?

ex :
    In data;
           abba, abraham, edie, Abba, edie
    After operation;
           abba, abraham, edie, Abba
+5
source share
4 answers

If you can sort the items in a container, a simple and relatively effective solution would be:

std::sort(data.begin(), data.end());
data.erase(std::unique(data.begin(), data.end()), data.end());
+10
source

I'm not sure there is a really good way to do this. What I would do is sort (in another array, if you need the original in measure) and then run it.

0
source

"set" . .

0

If you really need to do this efficiently, then you first need to do the sorting in place, and then go through the container yourself, instead of using std :: unique, select unique elements in a new vector, and then make a replacement.

I just checked the source code of std :: unique, it will move a lot when searching for one duplicate, the movement will degrade the operation of the vector.

0
source

All Articles