set_union(),set_intersection(),set_difference()
- set_union: 构造一个有序序列,包含两个有序序列的并集。
- set_intersection: 构造一个有序序列,包含两个有序序列的交集。
- set_difference: 构造一个有序序列,该序列保留第一个有序序列中存在而第二个有序序列中不存在的元素。
vector<int> vecIntA;
vecIntA.push_back(1);
vecIntA.push_back(3);
vecIntA.push_back(5);
vecIntA.push_back(7);
vecIntA.push_back(9);
vector<int> vecIntB;
vecIntB.push_back(1);
vecIntB.push_back(3);
vecIntB.push_back(5);
vecIntB.push_back(6);
vecIntB.push_back(8);
vector<int> vecIntC;
vecIntC.resize(10);
//并集
set_union(vecIntA.begin(), vecIntA.end(), vecIntB.begin(), vecIntB.end(), vecIntC.begin()); //vecIntC : {1,3,5,6,7,8,9,0,0,0}
//交集
fill(vecIntC.begin(),vecIntC.end(),0);
set_intersection(vecIntA.begin(), vecIntA.end(), vecIntB.begin(), vecIntB.end(), vecIntC.begin()); //vecIntC: {1,3,5,0,0,0,0,0,0,0}
//差集
fill(vecIntC.begin(),vecIntC.end(),0);
set_difference(vecIntA.begin(), vecIntA.end(), vecIntB.begin(), vecIntB.end(), vecIntC.begin()); //vecIntC: {7,9,0,0,0,0,0,0,0,0}
具体看如下代码:
#include <iostream>
using namespace std;
#include "string"
#include <vector>
#include <list>
#include "set"
#include <algorithm>
#include "functional"
#include "iterator" //输出流迭代器的头文件
void printV(vector<int> &v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout<<"it: "<<*it<<endl;
}
}
void my_union()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(3);
v1.push_back(5);
vector<int> v2;
v2.push_back(2);
v2.push_back(4);
v2.push_back(6);
vector<int> v3;
v3.resize(v1.size() + v2.size());
//构造一个有序序列,包含两个序列的并集
set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
printV(v3); //输出: 1 2 3 4 5 6
}
void my_intersection()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(5);
vector<int> v2;
v2.push_back(2);
v2.push_back(4);
v2.push_back(6);
vector<int> v3;
v3.resize(v1.size() + v2.size());
//构造一个有序序列,求两个序列的交集
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
printV(v3); //输出: 2 0 0 0 0 0
}
void my_difference()
{
vector<int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(5);
vector<int> v2;
v2.push_back(2);
v2.push_back(4);
v2.push_back(6);
vector<int> v3;
v3.resize(v1.size() + v2.size());
//构造一个有序序列,保留在第一个集合中出现但是没有在第二个集合中出现的元素
set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
printV(v3); //输出: 1 5 0 0 0 0
}
void main()
{
//my_union();
//my_intersection();
my_difference();
}