set_union 与多集容器?

2022-01-24 00:00:00 containers c++ stl stl-algorithm

当一个或两个输入容器是具有重复对象的多重集时,算法 std:set_union 的返回是什么?复制人会迷路吗?

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?

假设例如:

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() );

输出会是什么?

推荐答案

来自标准,25.3.5:

From the standard, 25.3.5:

通过定义 union() 以包含每个元素的最大出现次数,intersection() 以标准方式将集合操作的语义推广到多重集合包含最小值,等等.

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.

因此,在您的示例中,结果将是 (1,1,1,2,2,3,4,0,0,0),因为您初始化了长度为 10 的向量.

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.

相关文章