如何在C++中删除矢量类型的重复项<string>?

How to remove duplicates of type vector<string> in C++?

本文关键字:lt string gt C++ 删除 类型      更新时间:2023-10-16

我知道防止重复的一个好方法是使用unordered_set。但是,当我想unordered_set<vector<string>>时,这种方法似乎不起作用。我该怎么做呢?例如,我想防止<"a", "b", "c">在我的unordered_set<vector<string>>中重复。

unordered_set<vector<string>>也可以在定义的类之外使用吗?

法典:

unordered_set<vector<string>> abc({"apple", "ball", "carrot"});
abc.insert({"apple", "ball", "carrot"});
cout << abc.size() << endl;     //abc.size() should be 1
有很多

方法可以消除重复项,从对象中构建集合就是其中之一。是std::set还是std::unordered_set由您决定,而决定通常取决于您能想出多好的哈希函数。

这反过来又需要对域的了解,例如,字符串向量代表什么以及它们可以具有什么值。 如果你确实想出了一个好的哈希,你可以像这样实现它:

struct MyHash
{
    std::size_t operator()(std::vector<std::string> const& v) const 
    {
        // your hash code here
        return 0; // return your hash value instead of 0
    }
};

然后,您只需使用该哈希值声明您的unordered_set

std::unordered_set<std::vector<std::string>, MyHash> abc;

我会说,一开始只使用std::set是一个安全的选择,除非你有一个很好的哈希函数。