在 std::vector<std::unordered_set上使用 std::unique(<T>>
Using std::unique() on a std::vector<std::unordered_set<T>>
这是我的问题:我有一个std::vector<std::unordered_set<int>>
。其中一些无序集合是相等的,但顺序不同(我知道无序集合中的顺序是不明确的)。为了去除重复项(在集合的数学意义上,例如{1,3,2}={3,2,1}),我曾想过使用std::unique()
,但这不起作用。搜索后,我甚至注意到向量中的数据需要排序,这在这种情况下没有意义。是否有删除std::vector<std::unordered_set<int>>
中重复项的功能?我可以自己做,我只是想知道我在摔跤比赛中是否错过了什么。此外,如果你知道如何使用不同的容器来解决这个问题,请告诉我。效率在这里不是一个大问题,在这种情况下,该向量中的元素不超过200个。
TLDR;如何删除std::vector<std::unordered_set<int>>
中的重复项?
效率在这里不是什么大问题
那就让我们疯狂吧!set
已经定义了operator<
,所以让我们快速构建它们吧!
std::vector<std::unordered_set<int>> v = ...;
std::sort(v.begin(), v.end(), [](auto const& lhs, auto const& rhs){
return std::set<int>(lhs.begin(), lhs.end()) <
std::set<int>(rhs.begin(), rhs.end());
});
v.erase(std::unique(v.begin(), v.end()), v.end());
就运行时而言,这当然很糟糕,但它确实有效!
或者,你可以制作一个unordered_set<unordered_set<int>>
,并提出一个独立于排序的哈希,这样你就不必一开始就做任何这些了。
谢谢大家。我听从了n.m的建议,因为我认为这确实是最简单的。看起来像这样:
std::vector<std::set<int>> resultP;
...............................................
// Remove the duplicate (without order), we want combinations not permutations.
std::vector<std::set<int>> resultC;
bool permAlreadyThere = false;
for (auto& perm : resultP)
{
for (auto& comb : resultC)
{
if (perm == comb)
{
permAlreadyThere = true;
break;
}
}
if (!permAlreadyThere) resultC.push_back(perm);
permAlreadyThere = false;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;
- 为什么STD :: MAP需要操作员&lt;以及我如何写一个
- std::vector::reserve(未知m),我知道m<<;N(通常)并且知道N
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- C++运算符<<调用::ostream而不是std::osttream
- 是std :: set&lt; std :: future&gt;不可能存在
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- C++重载<<具有typedef'd std::vector
- 以x的倍数填充前导零,使用std::cout<<std::十六进制
- 错误:没有匹配'运算符<<"在'std::cout
- std::pair的默认构造函数<>将基本类型(int等)设置为零
- std::ostream&operator< & lt; (std:: ostream&压力,压力& &;val)
- 将std::endl传递给std::operator<<
- std::映射<>或std::vector<>在处理大型标志集时
- 重载& lt; & lt;使用命名空间std