C++ 将向量的元素添加到无序集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12850927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:40:46  来源:igfitidea点击:

adding elements of a vector to an unordered set

c++vectorunordered-set

提问by jamesatha

Is there an easy way to add all the elements of a vectorto 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

有没有一种简单的方法可以将 a 的所有元素添加vector到 an 中unordered_set?它们属于同一类型。现在,我正在使用 for 循环并想知道是否有更好的方法来做到这一点

回答by mythagel

If you're constructing the unordered_set then:

如果您正在构建 unordered_set,则:

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

回答by Karthik T

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

如果我的语法有任何小错误,请原谅我,但您可以尝试std::copy 函数,它就是为此目的而设计的。

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