C++ STL Set 快速入門

wgd7 9年前發布 | 1K 次閱讀 C/C++

Set

一 、簡介

set是一個集合,其中元素有序,排序的方式按照指定的方式來排序,不指定則默認按照升序排列
set中元素不可以相同;比較兩個set相同,他們的排序方式和元素都要相同;不能直接改變元素的值,需要先刪除,再插入。

set經常用來保存一組數據,他們獲得和使用的順序無關緊要,只需要考慮是否是在集合中即可。

二 、示例代碼

    #include <iostream>

#include <iterator>  
#include <algorithm>  
#include <set>  
using namespace std;  
struct classcomp     
{    
    bool operator()(const char& lhs,const char& rhs)    
    {    
        return lhs > rhs;    
    }    
};   
char array[] = {'e','f','g'};  
int _tmain(int argc, _TCHAR* argv[])  
{  
    set<char,classcomp> myset;  
    myset.insert('a');  
    myset.insert('b');  
    myset.insert('c');  
    copy(myset.begin(),myset.end(),ostream_iterator<char>(cout," "));  
    cout<<endl;  
    cout<<myset.insert('d').second<<endl;  
    //Now a b c d  

    myset.insert(array,array+3);  
    copy(myset.begin(),myset.end(),ostream_iterator<char>(cout," "));  
    cout<<endl;  
    //Now g f e d c b a  
    myset.erase('d');  
    //Now g f e c b a  
    myset.erase(myset.begin());  
    //Now f e c b a   
    copy(myset.begin(),myset.end(),ostream_iterator<char>(cout," "));  
    cout<<endl;  
    //myset.clear();//清空set  
    set<char,classcomp>::iterator it= myset.begin();  
    if ((it = myset.find('k')) == myset.end())  
    {  
        cout<<"Can not find K in this set"<<endl;  
    }  
    cout<<"Current size is :"<<myset.size()<<endl;  
}  </pre> 


 本文由用戶 wgd7 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!