功能描述:
求两个集合的并集
函数原型;
set_union(iterator beg1,iterator end1,iterator beg2,iterator end2,iterator dest);
//求两个集合的并集
//注意:两个集合必须是有序序列
//beg1 容器1开始迭代器
//end1 容器1结束迭代器
//beg2 容器2开始迭代器
//end2 容器2结束迭代器
//dest 目标容器开始迭代器
#include <iostream>
using namespace std;
#include<vector>
#include<algorithm>
void MyPrint(int val)
{
cout << val << " ";
}
void test01()
{
vector<int>v1;
vector<int>v2;
for (int i = 0; i < 10; i++)
{
v1.push_back(i);
v2.push_back(i + 5);
}
for_each(v1.begin(), v1.end(), MyPrint);
cout << endl;
for_each(v2.begin(), v2.end(), MyPrint);
cout << endl;
vector<int>vTarget;
//目标容器需要提前开辟空间
//最特殊情况 两容器没有交集 并集就是两个容器size相加
vTarget.resize(v1.size()+ v2.size());
vector<int>::iterator itEnd = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
for_each(vTarget.begin(), itEnd, MyPrint);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
输出结果:
0 1 2 3 4 5 6 7 8 9
5 6 7 8 9 10 11 12 13 14
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
总结:
求并集的两个集合必须是有序序列
目标容器开辟空间需要两个容器相加
set_union返回值即是并集中最后一个元素的位置