2017-03-20 37 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儘管如此,除非你有一個好的散列函數在你的腦海裏。