- #include <iostream>
- #include <set>
- #include <algorithm>
- #include <iterator>
- using namespace std;
- template <class T>
- struct display
- {
- void operator()(const T &x)
- {
- cout<<x<<" ";
- }
- };
- int main()
- {
- int ia1[]={1,3,5,7,9,11};
- int ia2[]={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: ";
- //兩個集合合併,相同元素個數取 max(m,n)。
- set_union(first1,last1,first2,last2,ostream_iterator<int>(cout," "));
- cout<<endl;
- first1=s1.begin();
- first2=s2.begin();
- cout<<"Intersection of s1 and s2: ";
- //兩個集合交集,相同元素個數取 min(m,n).
- set_intersection(first1,last1,first2,last2,ostream_iterator<int>(cout," "));
- cout<<endl;
- first1=s1.begin();
- first2=s2.begin();
- cout<<"Intersection of s1 and s2: ";
- //兩個集合差集 就是去掉S1中 的s2
- set_difference(first1,last1,first2,last2,ostream_iterator<int>(cout," "));
- cout<<endl;
- first1=s1.begin();
- first2=s2.begin();
- cout<<"Intersection of s1 and s2: ";
- //兩個集合對稱差集:就是取兩個集合互相沒有的元素 。兩個排序區間,元素相等指針後移,不等輸出小的並前進
- //相同元素的個數 abs(m-n)
- set_symmetric_difference(first1,last1,first2,last2,ostream_iterator<int>(cout," "));
- cout<<endl;
- return 0;
- }
編程第六十三、六十四天
c++ algorithm set方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.