Remove duplicates from a listlt;intgt;(从列表中删除重复项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;
});
这篇关于从列表中删除重复项<int>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从列表中删除重复项<int>


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01