确定是否在C ++ 11中发生冲突unordered_set [英] Determine if collision occurred in C++11 unordered_set

查看:66
本文介绍了确定是否在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
}

这篇关于确定是否在C ++ 11中发生冲突unordered_set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆