C++ 将集合追加到另一个集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2607235/
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-28 00:03:49  来源:igfitidea点击:

append set to another set

c++insertset

提问by mr.bio

Is there a better way of appending a set to another set than iterating through each element ?

有没有比遍历每个元素更好的方法将一个集合附加到另一个集合?

i have :

我有 :

set<string> foo ;
set<string> bar ;

.....

for (set<string>::const_iterator p = foo.begin( );p != foo.end( ); ++p)
    bar.insert(*p);

Is there a more efficient way to do this ?

有没有更有效的方法来做到这一点?

回答by CB Bailey

You can insert a range:

您可以插入一个范围:

bar.insert(foo.begin(), foo.end());

回答by Eddy Pronk

It is not a more efficient but less code.

它不是更有效,而是更少的代码。

bar.insert(foo.begin(), foo.end());

Or take the union which deals efficiently with duplicates. (if applicable)

或者采用有效处理重复项的联合。(如果适用)

set<string> baz ;

set_union(foo.begin(), foo.end(),
      bar.begin(), bar.end(),
      inserter(baz, baz.begin()));