Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which STL container to use if I want it to ignore duplicated elements?

Tags:

c++

set

stl

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?

like image 767
Igor Avatar asked Dec 03 '22 06:12

Igor


1 Answers

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 std::unique algorithm.

like image 132
Jeff Foster Avatar answered Dec 08 '22 00:12

Jeff Foster