append set to another set

2019-02-07 16:23发布

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 ?

标签: c++ insert set
2条回答
放我归山
2楼-- · 2019-02-07 16:40

You can insert a range:

bar.insert(foo.begin(), foo.end());
查看更多
相关推荐>>
3楼-- · 2019-02-07 16:50

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()));
查看更多
登录 后发表回答