
Hello, Given a std::vector<T> and a Compare<T> comparator, how can I: 1. determine the number of different elements in the vector? 2. get iterators to the list of distinct elements in the vector? My naive implementation for 1 is: /// v is const-ref to a std::vector<T> std::vector<T>::size_type distinct = v.empty()? 0: 1; std::vector<T>::const_iterator j; for (std::vector<T>::const_iterator i = v.begin()+1; i!=v.end(); ++i) { j = std::find(v.begin(), i, *i, Compare<T>()); if (j!=i) ++distinct; } Obviously, this is of worst order n*(n+1)/2. I'm sure a better order can be achieved. I don't quite see how to do 2. Does anything in the C++ std lib or boost facilitate this? Regards,

On 10 April 2010 17:22, Hicham Mouline
Given a std::vector<T> and a Compare<T> comparator, how can I:
1. determine the number of different elements in the vector? 2. get iterators to the list of distinct elements in the vector?
With 2 iterators b and e, std::sort(b, e); m = std::unique(b, e, Compare<T>()); Then you have the std::distance(b, m) unique elements available in the range [b, m). (Note that as a generic C++ question, this boost-specific list is perhaps not the best place to ask. You might consider something like Freenode's ##C++ IRC channel instead, where the medium means you would likely get a faster response as well, as the question doesn't require investigation or bug-hunting.)
participants (2)
-
Hicham Mouline
-
Scott McMurray