2017-03-20 38 views
0

我知道防止重复的好方法是使用unordered_set。但是,当我想要一个unordered_set<vector<string>>时,此方法似乎不起作用。我怎么能这样做呢?例如,我想阻止<"a", "b", "c">在我的unordered_set<vector<string>>中被复制。如何删除C++中类型向量<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 
+0

我想我必须自己定义一个散列?不知道该怎么做,虽然 –

+3

你可以发布一个非常小的例子,它增加了{“a”,“b”,“c”}两次,并检查集的大小()? –

+0

它不编译,因为没有为'unordered_set >' –

回答

0

有多种方式来摆脱重复的,建立一套从你的对象是其中之一。不管它是std::set还是std::unordered_set都由你来决定,而这个决定通常取决于你提供的散列函数有多好。

这反过来需要知道域,例如,你的字符串向量代表什么,他们可以拥有什么样的价值。如果你不拿出一个好的哈希,你可以这样实现它:

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

我会说这是一个安全的赌注,只是:

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尽管如此,除非你有一个好的散列函数在你的脑海里。