简体   繁体   English

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

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

I know that a good way to prevent duplicates is to use an unordered_set . 我知道防止重复的一个好方法是使用unordered_set However, this method does not seem to work when I want to have an unordered_set<vector<string>> . 但是,当我想要一个unordered_set<vector<string>>时,此方法似乎不起作用。 How can I go about doing this? 我该怎么做呢? For example, I want to prevent <"a", "b", "c"> from being duplicated in my unordered_set<vector<string>> . 例如,我想防止<"a", "b", "c">在我的unordered_set<vector<string>>重复。

Can this unordered_set<vector<string>> be used outside the defined class as well? 是否可以在定义的类之外使用此unordered_set<vector<string>>

Code: 码:

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

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

There is a number of ways to get rid of duplicates, building a set out of your objects is one of them. 有很多方法可以消除重复项,其中一种是根据对象构建集合。 Whether it is going to be std::set or std::unordered_set is up to you to decide, and the decision usually depends on how good of a hash fuction can you come up with. 究竟是std::set还是std::unordered_set取决于您自己决定,而决定通常取决于您能否提出一个哈希函数。

This in turn requires the knowledge of the domain, eg what your vectors of strings represent and what values can they have. 反过来,这需要了解域,例如,您的字符串向量表示什么以及它们可以具有什么值。 if you do come up with a good hash, you can implement it like this: 如果确实提出了一个很好的哈希,则可以这样实现:

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
    }
};

Then you just declare your unordered_set with that hash: 然后,您只需使用该哈希值声明unordered_set

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

I would say it's a safe bet to just go with a std::set at first though, unless you have a good hash function on your mind. 我会说,一开始只选择std::set是一个安全的选择,除非您脑海中有一个很好的哈希函数。

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

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