Take the 2-minute tour ×

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)

Is there a more efficient way to do this ?

share|improve this question
add comment

2 Answers

up vote 28 down vote accepted

You can insert a range:

bar.insert(foo.begin(), foo.end());
share|improve this answer
Interestingly C++03 guarantees linear time!? as the range is sorted (it comes from another set), but a relatively recent draft of C++0x has deleted this guarantee. –  Charles Bailey Apr 9 '10 at 12:22
add comment

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()));
share|improve this answer
I'm not sure what you mean by '...deals efficiently with duplicates'. Do you think that insert is not efficient with duplicates, sufficient to warrant using a third container? –  Charles Bailey Apr 9 '10 at 13:32
@Charles: Good question. There are cases where you would want to keep your sets and need a third container anyway. About efficiency: Josuttis says it is linear (at most, 2*(n + m) - 1 comparisons) –  Eddy Pronk Apr 9 '10 at 14:00
set_union may be linear, but inserter probably isn't. –  UncleBens Apr 9 '10 at 20:51
@UncleBens, in C++11 inserter can be made linear by using the end() iterator as a hint rather than begin(). –  Mark Ransom May 2 at 21:49
add comment

Your Answer


