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

时间:2017-03-20 15:04:54

标签: c++ vector unordered-set

我知道防止重复的好方法是使用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

1 个答案:

答案 0 :(得分:0)

有许多方法可以摆脱重复,建立一个对象的集合就是其中之一。是由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,除非你有一个很好的哈希函数。