STL---set基本使用--取集合的交、並、差、對稱差

轉自:http://blog.sina.com.cn/s/blog_4c98b9600100az2v.html


set是集合,其底層數據結構是紅黑樹,STL中set、map均採用紅黑樹結構作爲底層支持,紅黑樹與AVL樹類似,是一種平衡查找樹。

set的特性是集合的基本特性:元素唯一性等。

通過algorithm中提供的set_intersection、set_union、set_difference、set_symmetric_difference四個函數,可以方便的實現集合的交、並、差、對稱差操作,很實用!

微軟幫助文檔中對集合(set)的解釋: “描述了一個控制變長元素序列的對象(注:set中的key和value是Key類型的,而map中的key和value是一個pair結構中的兩個分 量)的模板類,每一個元素包含了一個排序鍵(sort key)和一個值(value)。對這個序列可以進行查找、插入、刪除序列中的任意一個元素,而完成這些操作的時間同這個序列中元素個數的對數成比例關 系,並且當遊標指向一個已刪除的元素時,刪除操作無效。”
而一個經過更正的和更加實際的定義應該是:一個集合(set)是一個容器,它其中所包含的元素的值是唯一的。這在收集一個數據的具體值的時候是有用的。集 閤中的元素按一定的順序排列,並被作爲集合中的實例。如果你需要一個鍵/值對(pair)來存儲數據,map是一個更好的選擇。一個集合通過一個鏈表來組 織,在插入操作和刪除操作上比向量(vector)快,但查找或添加末尾的元素時會有些慢。

下面是四個函數的標準用法:

#include <algorithm>
#include <iostream>
#include <set>
using namespace std;
 
int main()
{
       int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
       set<int> S( a, a + 9 );
      
       int b[] = { 3, 6, 8, 9 };
       set<int> S2( b, b + 4 );
      
       set<int>::iterator site;
 
       set<int> Su;
       set<int> Si;
       set<int> Sd;
       set<int> Ssd;
      
       //交集
       set_intersection( S.begin(), S.end(),
                                   S2.begin(), S2.end(),
                                   inserter( Si, Si.begin() ) );
                                  
       //並集
       set_union( S.begin(), S.end(),
                     S2.begin(), S2.end(),
                        inserter( Su, Su.begin() ) );
                       
       //差集
       set_difference( S.begin(), S.end(),
                                S2.begin(), S2.end(),
                                   inserter( Sd, Sd.begin() ) );
      
       //對稱差集
       set_symmetric_difference( S.begin(), S.end(),
                                                S2.begin(), S2.end(),
                                                 inserter( Ssd, Ssd.begin() ) );
                                                
      
       site = Si.begin();
       cout<<"the intersection of S and S2 is : ";
       while( site != Si.end() )
       {
              cout<< *site <<" ";
              ++ site;
       }
       cout<<endl;
      
       site = Su.begin();
       cout<<"the union of S and S2 is : ";
       while( site != Su.end() )
       {
              cout<< *site <<" ";
              ++ site;
       }
       cout<<endl;
      
       site = Sd.begin();
       cout<<"the difference of S and S2 is : ";
       while( site != Sd.end() )
       {
              cout<< *site <<" ";
              ++ site;
       }
       cout<<endl;
      
       site = Ssd.begin();
       cout<<"the symmetric difference of S and S2 is : ";
       while( site != Ssd.end() )
       {
              cout<< *site <<" ";
              ++ site;
       }
       cout<<endl;
      
       return 0;
}


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