Search code examples
c++stlcontainersstl-algorithm

set_union with multiset containers?


What's the return of the algorithm std:set_union when one or both input containers are multisets with duplicated objects? Do dups get lost?

Let's suppose for example:

multiset<int> ms1;
ms1.insert(1);
ms1.insert(1);
ms1.insert(1);
ms1.insert(2);
ms1.insert(3);

multiset<int> ms2;
ms2.insert(1);
ms2.insert(1);
ms2.insert(2);
ms2.insert(2);
ms2.insert(4);

vector<int> v(10);
set_union( ms1.begin(), ms1.end(), ms2.begin(), ms2.end(), v.begin() );

What would the output be?


Solution

  • From the standard, 25.3.5:

    The semantics of the set operations are generalised to multisets in a standard way by defining union() to contain the maximum number of occurrences of every element, intersection() to contain the minimum, and so on.

    So in your example, the result will be (1,1,1,2,2,3,4,0,0,0), since you initialised the vector with length 10.