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>
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
