set_unition(并集),set_intersection(交集),set_difference(差集) 3 个函数的写法

set_??(a.begin(),a.end(),b.begin(),b.end(),inserter(x,x.begin());

#include<iostream>
#include<string>
#include <set>
#include <algorithm>
using namespace std;
int main(){
	set<int>a;
	set<int>b;
	set<int>x;
	a.insert(5);
	a.insert(6);
	a.insert(7);
	b.insert(4);
	b.insert(6);
	b.insert(8);
	set<int>::iterator ip;
	for(ip=a.begin();ip!=a.end();ip++){
	cout << "A的集合为" << *ip; 
}cout << endl;
	for(ip=b.begin();ip!=b.end();ip++){
	cout << "B的集合为" << *ip;
}cout << endl;
	set_union(a.begin(),a.end(),b.begin(),b.end(),inserter(x,x.begin()));
	for(ip=x.begin();ip!=x.end();ip++){
	cout << "并集:" << *ip;
}cout << endl;
	x.clear() ;
	set_intersection(a.begin(),a.end(),b.begin(),b.end(),inserter(x,x.begin()));
		for(ip=x.begin();ip!=x.end();ip++){
	cout << "交集:" << *ip;
}cout << endl;
	x.clear();
	set_difference(a.begin(),a.end(),b.begin(),b.end(),inserter(x,x.begin()));
	for(ip=x.begin();ip!=x.end();ip++)
	cout << "差集:" <<*ip;
	cout <<endl; return 0;
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐