在 std::vector<std::unordered_set上使用 std::unique(<T>>

Using std::unique() on a std::vector<std::unordered_set<T>>

本文关键字:std lt gt unique vector unordered set      更新时间:2023-10-16

这是我的问题:我有一个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;
}