【问题标题】:How to remove duplicates of type vector<string> in C++?如何在 C++ 中删除类型 vector<string> 的重复项?
【发布时间】:2017-08-11 22:31:14
【问题描述】:

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

这个unordered_set&lt;vector&lt;string&gt;&gt; 也可以在定义的类之外使用吗?

代码:

unordered_set<vector<string>> abc({"apple", "ball", "carrot"});
abc.insert({"apple", "ball", "carrot"});

cout << abc.size() << endl;     //abc.size() should be 1

【问题讨论】:

  • 我想我必须自己定义一个哈希?虽然不知道怎么做
  • 你能发布一个非常小的例子,它添加 {"a", "b", "c"} 两次,并检查集合的 size() 吗?
  • 简单地使用 std::set 怎么样?
  • 可能与此重复:stackoverflow.com/q/29855908/10077
  • 我收到了一个类似的错误,提示“C++ 标准没有为这种类型提供哈希值。”似乎很清楚。查找模板参数以了解如何添加哈希器。我只是用一个很少使用的字符作为连接符连接所有字符串。如果连接符是 '+',它不会知道 {"a+b+c"} 和 {"a", "b", "c"} 之间的区别,但也许你知道没有使用 '\0'在任何字符串中? (虽然 xyz 似乎很可能)

标签: c++ vector unordered-set


【解决方案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 是一个安全的选择,除非你有一个好的哈希函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2011-05-25
    • 2018-02-25
    相关资源
    最近更新 更多