Possible Duplicate:
How to make elements of vector unique? (remove non adjacent duplicates)
Remove duplicates from a list<int>
I have list of pointers like
std::list<Person*> persons;
and there is duplicates in this list during filling. How to remove duplicates and stay only unique pointers in list ?
If you can change the order of the elements, then first sort the list with list::sort, then remove the duplicates with list::unique.
On the other hand, you could use an std::set. It’s elements are unique, ordered, and the insert method fails if an element is already present in the set.
Bear in mind that the time complexity of insertion of single elements is logarithmic, whereas adding elements to the front or back of a list is constant time. On the other hand,
std::list::sortisN*log(N), andstd::uniqueis linear. So if you intent to perform these duplicate removals frequently, you are better off with using anstd::setin the first place. Also note that in C++11 there is std::unordered_set, which has element uniqueness and average constant complexity for insertions and removals.