adding elements of a vector to an unordered set

孤者浪人 提交于 2019-12-09 14:05:41

问题


Is there an easy way to add all the elements of a vector to an unordered_set? They are of the same type. Right now, I am using a for loop and was wondering if there is a better way to do it


回答1:


If you're constructing the unordered_set then:

std::vector<int> v;
std::unordered_set<int> s(v.begin(), v.end());



回答2:


Forgive me if my syntax has any minor bugs, but you can try the std::copy function, its meant for this purpose.

std::vector<int> v;
std::unordered_set<int> s;
std::copy(v.begin(),v.end(),std::inserter(s,s.end()));


来源:https://stackoverflow.com/questions/12850927/adding-elements-of-a-vector-to-an-unordered-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!