編程第六十三、六十四天

c++ algorithm set方法
  1. #include <iostream>  
  2. #include <set>  
  3. #include <algorithm>  
  4. #include <iterator>  
  5. using namespace std;  
  6.   
  7. template <class T>  
  8. struct display  
  9. {  
  10.     void operator()(const T &x)  
  11.     {  
  12.         cout<<x<<" ";  
  13.     }  
  14.       
  15. };  
  16. int main()  
  17. {  
  18.     int ia1[]={1,3,5,7,9,11};  
  19.     int ia2[]={1,1,2,3,5,8,13};  
  20.       
  21.     multiset<int> s1(ia1,ia1+6);  
  22.     multiset<int> s2(ia2,ia2+7);  
  23.     for_each(s1.begin(),s1.end(),display<int>());  
  24.     cout<<endl;  
  25.     for_each(s2.begin(),s2.end(),display<int>());  
  26.     cout<<endl;  
  27.       
  28.     multiset<int>::iterator first1 = s1.begin();  
  29.     multiset<int>::iterator last1 = s1.end();  
  30.     multiset<int>::iterator first2 = s2.begin();  
  31.     multiset<int>::iterator last2 = s2.end();  
  32.       
  33.     cout<<"union of s1 and s2: ";  
  34.     //兩個集合合併,相同元素個數取 max(m,n)。   
  35.     set_union(first1,last1,first2,last2,ostream_iterator<int>(cout," "));  
  36.     cout<<endl;  
  37.       
  38.     first1=s1.begin();  
  39.     first2=s2.begin();  
  40.     cout<<"Intersection of s1 and s2: ";  
  41.     //兩個集合交集,相同元素個數取 min(m,n).  
  42.     set_intersection(first1,last1,first2,last2,ostream_iterator<int>(cout," "));   
  43.     cout<<endl;  
  44.       
  45.     first1=s1.begin();  
  46.     first2=s2.begin();  
  47.     cout<<"Intersection of s1 and s2: ";  
  48.     //兩個集合差集 就是去掉S1中 的s2   
  49.     set_difference(first1,last1,first2,last2,ostream_iterator<int>(cout," "));   
  50.     cout<<endl;  
  51.        
  52.     first1=s1.begin();  
  53.     first2=s2.begin();  
  54.     cout<<"Intersection of s1 and s2: ";  
  55.     //兩個集合對稱差集:就是取兩個集合互相沒有的元素 。兩個排序區間,元素相等指針後移,不等輸出小的並前進   
  56.     //相同元素的個數 abs(m-n)   
  57.     set_symmetric_difference(first1,last1,first2,last2,ostream_iterator<int>(cout," "));   
  58.     cout<<endl;  
  59.       
  60.       
  61.     return 0;  
  62. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章