关联容器 set

//set的键与值的类型相同,且不能出现重复值。
#include<iostream>
#include<string>
#include<set>
#include<algorithm>
#include<iterator>
void output(const std::string &s){
	std::cout<<s<<" ";
} 

int main(void){
	using namespace std;
	const int N=6;
	string s1[N]={"buffon","thinkers","for","heavy","can","for"};
	string s2[N]={"metal","any","food","elegant","deliver","for"};
	
	set<string> A(s1,s1+N);
	set<string> B(s2,s2+N);
	
	ostream_iterator<string,char> out(cout," ");  //声明输出迭代器 
	cout << "Set A:";
	copy(A.begin(),A.end(),out);                   // A
	cout << endl;
		
	cout << "Set B:";
	copy(B.begin(),B.end(),out);                   //  B
	cout << endl;
	
	cout << "Union of A and B:\n";                   //A ∪ B 
	set_union(A.begin(),A.end(),B.begin(),B.end(),out);
	cout << endl;
	
	cout << "Intersection of A and B:\n";            //A ∩B 
	set_intersection(A.begin(),A.end(),B.begin(),B.end(),out);
	cout << endl;
	
	cout << "Differencr of A and B";                 //A - B 
	set_difference(A.begin(),A.end(),B.begin(),B.end(),out);
	cout << endl;
	
	set<string> C;
	cout << "Set C:\n";                            //A∪B-->C
	set_union(A.begin(),A.end(),B.begin(),B.end(),insert_iterator< set<string> >(C,C.begin()));
	/*
	*  这里不能使用  C.begin() 作为输出迭代器,因为C初始大小为0,空间不足无法进行赋值,只能以插入迭代
	*  器插入元素 ,且C.begin()被关联集合C视为一个常量迭代器 ,不能作为输出迭代器。 
	*/
	copy(C.begin(),C.end(),out);
	//set_intersection(C.begin(),C.end(),C.begin(),C.end(),out);
	cout << endl;
	
	string  s3("grungy");
	C.insert(s3);
	cout << "Set C after insertion:\n";
	//copy(C.begin(),C.end(),out);
	for_each(C.begin(),C.end(),output);   //两种方式都可以输出。 
	
	cout << endl;
	
	cout << "Showing a range:\n";//获得从第一个不小于ghost的元素到第一个大于spook的元素的区间,并输出 
	//copy(C.lower_bound("ghost"),C.upper_bound("spook"),out);
	for_each(C.lower_bound("ghost"),C.upper_bound("spook"),output); //两种方式都可以输出。
	
	cout << endl;
	
		
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值