从列表中删除重复项<int>
使用 STL 算法(尽可能多地),例如 remove_if()
和 list::erase
,是否有一种很好的方法可以从定义为的列表中删除重复项以下:
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
请注意,list::unique()
仅在连续元素中出现重复时才有效.就我而言,无论它们在列表中的位置如何,都必须消除所有重复项.此外,去除重复意味着在最终结果中只保留每个元素的一个副本.
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.
不能使用 l.sort()
后跟 l.unique()
的选项,因为这会破坏列表的顺序.
The option to l.sort()
followed by l.unique()
cannot be availed as that will destroy the order of the list.
推荐答案
使用 list::remove_if
成员函数、临时散列集和 lambda 表达式.
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;
});
相关文章