确定是否在C ++ 11中发生冲突unordered_set
我正在使用C ++ 11,并且尝试将元素添加到无序集合中,如果我已经将元素添加到unordered_set中,则我不想再次添加它(即,不添加cat)再次回到下面的无序集合.
I am playing around with C++11 and I am trying to add elements to an unordered set and if I already added an element to my unordered_set I don't want to add it again (i.e.) don't add cat again to the unordered set below.
std::unordered_set<std::string> s;
std::vector<std::string> myString;
myString.push_back("cat");
myString.push_back("dog");
myString.push_back("bird");
myString.push_back("cat");
for(auto &i : myString){
//add elements from myString to unordered_set s
}
我不确定如何执行此操作.我意识到我需要一个等于我 s.insert(i)
的 std :: pair
,但是我不太确定如何设置它,所以我可以做到这一点.
I am not exactly sure how to do this. I realize that I need to have a std::pair
equal to my s.insert(i)
however I'm not quite sure how to set this up so I can do this.
任何帮助将不胜感激
您为什么要担心? std :: unordered_set
仅包含唯一元素(如果已经存在,则不会自动添加),但是有一个 find()
函数:
Why are you concerned? std::unordered_set
only contains unique elements (automatically doesn't add if it already exists), but there is a find()
function:
for(auto &i : myString){
if(s.insert(i).second)
//inserted
else
//already exists
}