2014-02-21 23 views
0

我在玩C++ 11,我試圖向無序集添加元素,如果我已經向unordered_set添加了一個元素,我不想添加它再次(即)不再將貓添加到下面的無序集。確定在C++中是否發生了碰撞11 unordered_set

​​

我不完全知道如何做到這一點。我知道我需要一個std::pair等於我的s.insert(i)但是我不太清楚如何設置這個,所以我可以做到這一點。

任何幫助,將不勝感激

回答

2

你爲什麼要關注? std::unordered_set只包含獨特的元素(如果它已經存在不自動加),但有一個find()功能:

for(auto &i : myString){ 
    if(s.insert(i).second) 
     //inserted 
    else 
     //already exists 
} 
+0

如何讓它返回關於元素是否被添加的布爾值? – user2604504

+0

@ user2604504看到編輯 – yizzlez

+0

@ user2604504 http://en.cppreference.com/w/cpp/container/unordered_set/insert 檢查返回值,如果插入 – balki

0
for(auto& i: myString) { 
    if(s.insert(i).second) std::cout << "inserted" << std::endl 
    else std::cout << "dupe" << std::endl; 
} 

unordered_set不會插入重複,無需檢查。

0

std::unordered_set包含一組獨特的對象。

這意味着它可以包含而不是包含重複項(如果operator==返回true,則認爲兩個元素相同)。

例子:

std::unordered_set<std::string> s; 
s.emplace("cat"); 
s.emplace("cat"); 
s.emplace("cat"); 

// At this point s only contains one std::string object. 

要從std::vector添加獨特的項目只需使用std::vector::insert這樣的:

s.insert(std::begin(vec), std::end(vec)); 

一個std::unordered_set不會插入一個元素,如果它已經包含的元素有等效的關鍵。

相關問題