Why do we need a call to the inserter function when doing set_union on a set?

I need to make the set_union function call for STL as follows:

set<int> a1, a2;

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

but not

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

why is that so?

+3
source share
1 answer

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

Since you are already dealing with installed <> objects, why don't you just write

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

?

+9
source

Source: https://habr.com/ru/post/1719693/


All Articles