tags:

views:

122

answers:

1

I am looking for some STL (but not boost) container, which after the following operations will contain 2 elements: "abc" and "xyz":

std::XContainer<string> string_XContainer;
string_XContainer.push_back("abc");
string_XContainer.push_back("abc");
string_XContainer.push_back("xyz");

By the way, I need it just in order to call string_XContainer.size() in the end, to get the total number of unique strings. So maybe I don't even need a container, and there is a more elegant way of doing it?

+18  A: 

std::set is the one you are after. A set will contain at most one instance of each element, compared according to some comparator function you define.

This would be one approach to get the number of unique strings. From your example, the strings were already in sorted order? If that's the case, then you could just create an array (or some other simple structure) and use the unique algorithm.

Jeff Foster
Yes, set is the container for this. @Igor Oks, but note that the order of the inserted elements will not be maintained in the set, I guess that is not required.
Naveen
It won't maintain insertion ordering but it will maintain strict weak ordering.
Nikola Smiljanić
Do not forget that unique only operates on sorted ranges. You can test if a range is sorted using the `std::adjacent_find(iBegin, iEnd, std::greater<value_type>()) == iEnd` trick and only apply `sort` if it's not.
Matthieu M.
Profile before you optimize: if std::sort already has O(N) behavior on sorted datasets (certainly possible), the adjacent_find doesn't help.
MSalters