简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM