集合算法
作者:互联网
set_union(),set_intersection(),set_difference()
set_union: 构造一个有序序列,包含两个有序序列的并集。
set_intersection: 构造一个有序序列,包含两个有序序列的交集。
set_difference: 构造一个有序序列,该序列保留第一个有序序列中存在而第二个有
序序列中不存在的元素。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void main()
{
vector<int> vectorA;
vectorA.push_back(1);
vectorA.push_back(3);
vectorA.push_back(5);
vectorA.push_back(7);
vectorA.push_back(9);
vector<int> vectorB;
vectorB.push_back(1);
vectorB.push_back(3);
vectorB.push_back(5);
vectorB.push_back(6);
vectorB.push_back(8);
vector<int> vectorC;
vectorC.resize(10);//长度为10,填充默认值0
cout << "------------vectorA-------------" << endl;
printVc(vectorA);
cout << "------------vectorB-------------" << endl;
printVc(vectorB);
//并集
set_union(vectorA.begin(), vectorA.end(), vectorB.begin(), vectorB.end(),
vectorC.begin());
cout << "--------------并集--------------" << endl;
printVc(vectorC);
//交集
fill(vectorC.begin(), vectorC.end(),0);
set_intersection(vectorA.begin(), vectorA.end(), vectorB.begin(), vectorB.end(),
vectorC.begin());
cout << "--------------交集--------------" << endl;
printVc(vectorC);
//差集
fill(vectorC.begin(), vectorC.end(), 0);//把此容器值改为0
set_difference(vectorA.begin(), vectorA.end(), vectorB.begin(), vectorB.end(),
vectorC.begin());
cout << "--------------差集--------------" << endl;
printVc(vectorC);
}
运行结果:
标签:begin,back,push,算法,集合,vectorA,vectorB,vectorC 来源: https://blog.csdn.net/weixin_42122527/article/details/93915407