jeudi 23 juin 2016

Fastest way to remove duplicates from a vector<>

As the title says, I have in my mind some methods to do it but I don't know which is fastest.

So let's say that we have a: vector<int> vals with some values

1

After my vals are added

sort(vals.begin(), vals.end());
auto last = unique(vals.begin(), vals.end());
vals.erase(last, vals.end());

2

Convert to set after my vals are added:

set<int> s( vals.begin(), vals.end() );
vals.assign( s.begin(), s.end() );

3

When i add my vals, i check if it's already in my vector:

if( find(vals.begin(), vals.end(), myVal)!=vals.end() )
    // add my val

4

Use a set from start

Ok, I've got these 4 methods, my questions are:

1 From 1, 2 and 3 which is the fastest?
2 Is 4 faster than the first 3?
3 At 2 after converting the vector to set, it's more convenabile to use the set to do what I need to do or should I do the vals.assign( .. ) and continue with my vector?

Aucun commentaire:

Enregistrer un commentaire