C++set 和 multiset的使用


最后一個自由支配的暑假,學一些自己感興趣的部分,也算為大三作准備。

C++中set集合的使用

定義一個int類型的集合

set<int> s;

set<int>::iterator it;

基本操作有如下:

s.inert(10);//插入元素10

s.erase(10);//刪除元素10

s.clear();//清空集合

s.size();//集合元素的個數

s.empty();//判斷集合是否為空

it=s.find(10);//查找集合中是否有元素10,有的話返回10,沒有返回s.end();

首先集合在數學的概念中就是互異性,不能有重復

需要注意的點:

1.是以中序遍歷去遍歷整個集合的,在插入的時候自動調整

2.遍歷的時候需要判斷一下集合是否為空;

3.插入的數默認從小到大排序 set<int>::iterator it; 

4.如果要從大到小的話 set<int>::reverse_iterator rit;

         for(rit=s.rbegin();rit!=s.rend();rit++)

         {

                  cout<<*rit<<" ";

         }

 

 

自定義比較函數,用到結構體

 1 #include<set>
 2 
 3 #include<string>
 4 
 5 #include<iostream>
 6 
 7 using namespace std;  8 
 9  
10 
11 struct Info 12 
13 { 14 
15          string name; 16 
17          float score; 18 
19          //重載 '<'操作符
20 
21          bool operator < (const Info &a)const
22 
23  { 24 
25                   //按照score從小到大排序 換為‘<’則為從大到小
26 
27                   return a.score>score; 28 
29  } 30 
31 }; 32 
33 int main() 34 
35 { 36 
37          set<Info> s; 38 
39  Info info; 40 
41         
42 
43          info.name="Jack"; 44 
45          info.score=99; 46 
47  s.insert(info); 48 
49         
50 
51          info.name="Tom"; 52 
53          info.score=56; 54 
55  s.insert(info); 56 
57         
58 
59          info.name="Nacy"; 60 
61          info.score=85; 62 
63  s.insert(info); 64 
65         
66 
67          info.name="Elano"; 68 
69          info.score=100; 70 
71  s.insert(info); 72 
73         
74 
75          set<Info>::iterator it; 76 
77          for(it=s.begin();it!=s.end();it++) 78 
79          cout<<(*it).name<<" : "<<(*it).score<<endl; 80 
81          return 0; 82 
83  
84 
85 }

結果:

 

 

mutiset:多重集合 和set最大的區別就是,它可以插入重復的元素,

如果刪除的話,相同的也一起刪除了;

如果查找的話,返回該元素的迭代器的位置,若有相同,返回第一個元素的地址;

其他使用和set基本類似。

#include<set> #include<string> #include<iostream>
using namespace std; int main() { //多重集合對象 
    multiset<string> ms; ms.insert("abc"); ms.insert("123"); ms.insert("111") ; ms.insert("aaa"); ms.insert("123"); ms.insert("bbb"); multiset<string>::iterator it; for(it=ms.begin();it!=ms.end();it++) { cout<<*it<<endl; } cout<<endl<<"集合的大小:"<<ms.size()<<endl; it=ms.find("123"); if(it!=ms.end()) { cout<<*it<<endl; } else cout<<"not found"<<endl; it=ms.find("43"); if(it!=ms.end()) { cout<<*it<<endl; } else cout<<"not found"<<endl; int n=ms.erase("123"); cout<<"共刪除:"<<n<<endl<<endl; for(it=ms.begin();it!=ms.end();it++) { cout<<*it<<endl; } return 0; } 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM