繁体   English   中英

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

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

我知道防止重复的一个好方法是使用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是一个安全的选择,除非您脑海中有一个很好的哈希函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM