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.
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.
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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With