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