tags:

views:

116

answers:

2

Hi

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 ?

+11  A: 

You can insert a range:

bar.insert(foo.begin(), foo.end());
Charles Bailey
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
+3  A: 

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()));
Eddy Pronk
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
@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
`set_union` may be linear, but inserter probably isn't.
UncleBens