从列表中删除重复项<int> [英] Remove duplicates from a list&lt;int&gt;

查看:24
本文介绍了从列表中删除重复项<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:

listl;

请注意,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>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆