append set to another set

C++InsertSet

C++ Problem Overview


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++ Solutions


Solution 1 - C++

You can insert a range:

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

Solution 2 - C++

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()));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmr.bioView Question on Stackoverflow
Solution 1 - C++CB BaileyView Answer on Stackoverflow
Solution 2 - C++Eddy PronkView Answer on Stackoverflow