5

i need to make the call to the set_union function of STL like this:

set<int> a1, a2;

set_union(a1.begin(), a1.end(), a2.begin(), a2.end(), inserter(a1, a1.begin());

and not

set_union(a1.begin(), a1.end(), a2.begin(), a2.end(), a1.begin());

why is that so?

Rohit Banga
  • 16,996
  • 26
  • 101
  • 179
  • 2
    The problem with the STL algorithms is that they have abstracted the containers using iterators, but this leaves them unable to modify the actual size of these containers, they can merely move the elements inside. – Matthieu M. Oct 09 '09 at 08:18

1 Answers1

11

a1.begin() is simply not an output iterator. inserter(a1,a1.begin()) returns an output iterator which will invoke the set's insert function for each element. But I'm not even sure whether the first version is even correct. You iterate over the same set you insert new elements into. (!)

Since you deal with set<> objects already, why don't you simply write

a1.insert(a2.begin(),a2.end());

?

sellibitze
  • 25,788
  • 3
  • 69
  • 91
  • sometimes we get too engrossed in the things and use complex techniques. i forgot that to do a set union an insert would be sufficient. thanks. – Rohit Banga Oct 09 '09 at 08:10