Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates from a list<int>

Tags:

c++

stl

Using STL algorithms (as much as possible) such as remove_if() and list::erase, is there a nice way to remove duplicates from a list defined as following:

list<int> l;

Please note that list::unique() only works if duplication occurs in consecutive elements. In my case, all duplicates have to be eliminated regardless of their position in the list. Moreover, removing duplicates mean preserving only one copy of each element in the final result.

EDIT: The option to l.sort() followed by l.unique() cannot be availed as that will destroy the order of the list.

like image 222
Jaywalker Avatar asked Feb 03 '11 11:02

Jaywalker


People also ask

How do I remove duplicates from a list set?

Remove duplicates from list using Set. To remove the duplicates from a list, you can make use of the built-in function set(). The specialty of set() method is that it returns distinct elements.

How do you remove duplicates from an input list in Python?

Approach: Create a dictionary and by default keep the count of every element to zero, using the default dict. If the count of elements is ZERO, increment the value in the dictionary and continue. If the count of element is greater than zero, Then remove the element from the given list using the remove() method.


1 Answers

Using the list::remove_if member function, a temporary hashed set, and lambda expression.

std::list<int> l;
std::unordered_set<int> s;

l.remove_if([&](int n) {
    return (s.find(n) == s.end()) ? (s.insert(n), false) : true;
});
like image 87
Blastfurnace Avatar answered Oct 10 '22 00:10

Blastfurnace