stl中set相关算法

stl一共提供了四种与set集合相关的算法,分别是并集,交集,差集,对称差集。

四个算法都至少有四个参数,分别表现两个区间。

以下程序测试四个set相关算法,欲使用它们,必须包含<algorithm>。

#include<iostream>
#include<set>
#include<iterator>
#include<algorithm>
using namespace std;
template <class T>
struct display{
void operator()(const T& x)
{
cout<<x<<' ';
}
};


int main(){
int ia1[6]={1,3,5,7,9,11};
int ia2[7]={1,1,2,3,5,8,13};

multiset<int>s1(ia1,ia1+6);
multiset<int>s2(ia2,ia2+7);

for_each(s1.begin(),s1.end(),display<int>());
cout<<endl;
for_each(s2.begin(),s2.end(),display<int>());
cout<<endl;

multiset<int>::iterator first1=s1.begin();
multiset<int>::iterator last1=s1.end();
multiset<int>::iterator first2=s2.begin();
multiset<int>::iterator last2=s2.end();

cout<<"Union of s1 and s2:";
set_union(first1,last1,first2,last2,ostream_iterator<int>(cout," ")); //并集
cout<<endl;

first1 = s1.begin();
first2 = s2.begin();
cout<<"Intersection of s1 and s2:";
set_intersection(first1,last1,first2,last2,ostream_iterator<int>(cout," ")); //交集
cout<<endl;

first1 = s1.begin();
first2 = s2.begin();
cout<<"Difference of s1 and s2 (s1-s2): ";
set_symmetric_difference(first1,last1,first2,last2,ostream_iterator<int>(cout," ")); //对称差集
cout<<endl;

first1 = s2.begin();
first2 = s1.begin();
last1 = s2.end();
last2 = s1.end();
cout<<"Difference of s2 and s1 (s2-s1): ";
set_difference(first1,last1,first2,last2,ostream_iterator<int>(cout," ")); //差集
cout<<endl;

}

执行结果如下:

1 3 5 7 9 11
1 1 2 3 5 8 13
Union of s1 and s2:1 1 2 3 5 7 8 9 11 13
Intersection of s1 and s2:1 3 5
Difference of s1 and s2 (s1-s2): 1 2 7 8 9 11 13
Difference of s2 and s1 (s2-s1): 1 2 8 13


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值