STL set之求交并差

#include <iostream>
#include <set>
#include <string>
#include <algorithm>
using namespace std;
struct compare
{
	bool operator ()(string s1,string s2)
	{
	return s1>s2;
	}///自定义一个仿函数
};
int main()
{
typedef std::set<string,compare> _SET;
_SET s;
s.insert(string("sfdsfd"));
s.insert(string("apple"));
s.insert(string("english"));
s.insert(string("dstd"));
cout<<"s1:"<<endl;
std::set<string,compare>::iterator it = s.begin();
while(it!=s.end())
cout<<*it++<<" ";


cout<<endl<<"s2:"<<endl;
_SET s2;
s2.insert(string("abc"));
s2.insert(string("apple"));
s2.insert(string("english"));
it = s2.begin();
while(it!=s2.end())
cout<<*it++<<" ";
cout<<endl<<endl;


string str[10];
string *end = set_intersection(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//求交集,返回值指向str最后一个元素的尾端
cout<<"result of set_intersection s1,s2:"<<endl;
string *first = str;
while(first<end)
cout <<*first++<<" ";
cout<<endl<<endl<<"result of set_union of s1,s2"<<endl;

end = std::set_union(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//并集 first = str;
while(first<end)
cout <<*first++<<" ";
cout<<endl<<endl<<"result of set_difference of s2 relative to s1"<<endl;
first = str;

end = std::set_difference(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//s2相对于s1的差集 while(first<end)
cout <<*first++<<" ";
cout<<endl<<endl<<"result of set_difference of s1 relative to s2"<<endl;
first = str;
end = std::set_difference(s2.begin(),s2.end(),s.begin(),s.end(),str,compare());//s1相对于s2的差集
while(first<end)
cout <<*first++<<" ";
cout<<endl<<endl;
first = str;
end = std::set_symmetric_difference(s.begin(),s.end(),s2.begin(),s2.end(),str,compare());//上面两个差集的并集 while(first<end)
cout <<*first++<<" ";
cout<<endl;
}

运行结果:


http://www.cnblogs.com/zhangchaoyang/articles/2026096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值