How to remove duplicate values ​​from a list in C ++?

I am new to C ++ and got into a problem. I use a list to store string values. Now I want to remove duplicate values ​​from this row. Can anyone tell me how to do this.

Any code sample would be highly appreciated.

+3
c ++
source share
5 answers

If the list is sorted, use its unique method.

If the list is not sorted (and you do not want to sort it):

set<string> found; for (list<string>::iterator x = the_list.begin(); x != the_list.end();) { if (!found.insert(*x).second) { x = the_list.erase(x); } else { ++x; } } 

To avoid copying rows into a set:

 struct less { template<class T> bool operator()(T &a, T &b) { return std::less<T>()(a, b); } }; struct deref_less { template<class T> bool operator()(T a, T b) { return less()(*a, *b); } }; void remove_unsorted_dupes(list<string> &the_list) { set<list<string>::iterator, deref_less> found; for (list<string>::iterator x = the_list.begin(); x != the_list.end();) { if (!found.insert(x).second) { x = the_list.erase(x); } else { ++x; } } } 
+14
source share

Use sort and then unique .

+12
source share

If you have std::list , you can remove duplicates with:

 yourlist.sort(); yourlist.unique(); 
+6
source share

Use unique ().

But first, the sort () list, or unique, will not do what you expect.

+3
source share

Solution 1:

 struct already_found { std::set<std::string> & theSet; bool operator()(const std::string& s) const { return !theSet.insert(s).second; } }; std::set<std::string> theSet; the_list.remove_if( the_list.begin(), the_list.end(), already_found(theSet) ); 

Solution 2 using shared_ptr

 struct already_found { boost::shared_ptr<std::set<std::string> > theSet; already_found() : theSet( new boost::shared_ptr<std::set<std::string> > ) { } bool operator()(const std::string& s) const { return !theSet->insert(s).second; } }; the_list.remove_if( the_list.begin(), the_list.end(), already_found(theSet) ); 

These shortcomings have the need to copy all the lines. You can optimize this a bit by storing pointers to strings and comparing them with custom comparisons.

0
source share

All Articles