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 ?
From stackoverflow
-
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. -
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()));
Charles Bailey : 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?Eddy Pronk : @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)UncleBens : `set_union` may be linear, but inserter probably isn't.
0 comments:
Post a Comment