NeomerArcana
NeomerArcana

Reputation: 2269

How to find distinct values in an STL container C++11

I might be too tired right now. How can you find the distinct values in a container, or range?

I've looked through the algorithms library but I can't see anything standard. I could've sworn there was a standard algorithm to do it.

Aside from having a container B which I only add elements from container A which don't already appear...

**EDIT: would be good to get a count of each too.... like... SQL in C++11

Upvotes: 2

Views: 679

Answers (1)

TemplateRex
TemplateRex

Reputation: 70526

Given an input vector v, you can do something like

std::sort(begin(v), end(v));              // O(N log N) where N = v.size()
auto it = std::unique(begin(v), end(v));  // O(N)

Equivalently (well not really, since you need extra memory, the above method is in-place), you can copy them into and out of a std::set:

std::set<T> s(begin(v), end(v));                 // O(N log N);
auto it = std::copy(begin(s), end(s), begin(v)); // O(N);

Note that in both cases you need to actually erase the removed elements

v.erase(it, end(v)); // O(K), where K is the number of removed duplicates

Upvotes: 3

Related Questions