set,顧名思義,就是數學上的集合——每個元素最多只出現一次,並且set中的元素已經從小到大排好序。
頭文件:#include<set>
常用的函數:
begin() 返回set容器的第一個元素的地址
end() 返回set容器的最后一個元素地址
clear() 刪除set容器中的所有的元素
empty() 判斷set容器是否為空
max_size() 返回set容器可能包含的元素最大個數
size() 返回當前set容器中的元素個數
erase(it) 刪除迭代器指針it處元素
樣例如下:

1 #include <iostream> 2 #include <set> 3 4 using namespace std; 5 6 int main() 7 { 8 set<int> s; 9 s.insert(1); 10 s.insert(2); 11 s.insert(3); 12 s.insert(1); 13 cout<<"set 的 size 值為 :"<<s.size()<<endl; 14 cout<<"set 的 maxsize的值為 :"<<s.max_size()<<endl; 15 cout<<"set 中的第一個元素是 :"<<*s.begin()<<endl; 16 cout<<"set 中的最后一個元素是:"<<*s.end()<<endl; 17 s.clear(); 18 if(s.empty()) 19 { 20 cout<<"set 為空 !!!"<<endl; 21 } 22 cout<<"set 的 size 值為 :"<<s.size()<<endl; 23 cout<<"set 的 maxsize的值為 :"<<s.max_size()<<endl; 24 return 0; 25 }
還有兩個功能類似的函數:count()和find()
1.count() :用來查找set中某個元素出現的次數。這個函數在set並不是很實用,因為一個鍵值在set只可能出現0或1次,這樣就變成了判斷某一鍵值是否在set出現過了。
2.find(): 用來查找set中某個元素出現的位置。如果找到,就返回這個元素的迭代器,如果這個元素不存在,則返回 s.end() 。 (最后一個元素的下一個位置,s為set的變量名)
樣例如下:

1 #include <iostream> 2 #include <set> 3 4 using namespace std; 5 6 int main() 7 { 8 set<int> s; 9 set<int>::iterator it; //創建一個他對應的迭代器 10 11 s.insert(1); 12 s.insert(2); 13 s.insert(3); 14 s.insert(1); 15 cout<<"set 中 1 出現的次數是 :"<<s.count(1)<<endl; 16 cout<<"set 中 4 出現的次數是 :"<<s.count(4)<<endl; 17 18 it1 = st1.find(4); //查找數據 19 if (it1 != st1.end()) //如果找到就輸出數據 20 { 21 cout << *it1 << endl; 22 } 23 24 return 0; 25 }
set的遍歷,需要用到迭代器,具體的方法見下面的代碼:
1 ##include <iostream> 2 #include<set> 3 using namespace std; 4 5 6 int main() 7 { 8 set<int> s; //創建一個int類型的set 9 10 s.insert(10); //插入數據 11 s.insert(30); 12 s.insert(20); 13 s.insert(40); 14 15 //遍歷數據,用迭代器遍歷數據 16 for (set<int>::iterator it = s.begin(); it != s.end(); ++it) 17 { 18 cout << *it << endl; 19 } 20 //這里用到了set中的元素已經從小到大排好序的性質 21 22 return 0; 23 }
最后,不得不提的就是結構體類型(struct )的set ,使用時必須要重載 '<' 運算符
1 #include<iostream> 2 #include<set> 3 #include<string> 4 using namespace std; 5 struct Info 6 { 7 string name; 8 double score; 9 bool operator < (const Info &a) const // 重載“<”操作符,自定義排序規則 10 { 11 //按score由大到小排序。如果要由小到大排序,使用“>”即可。 12 return a.score < score; 13 } 14 }; 15 int main() 16 { 17 set<Info> s; 18 Info info; 19 20 //插入三個元素 21 info.name = "Jack"; 22 info.score = 80; 23 s.insert(info); 24 info.name = "Tom"; 25 info.score = 99; 26 s.insert(info); 27 info.name = "Steaven"; 28 info.score = 60; 29 s.insert(info); 30 31 set<Info>::iterator it; 32 for(it = s.begin(); it != s.end(); it++) 33 cout << (*it).name << " : " << (*it).score << endl; 34 return 0; 35 } 36 /* 37 運行結果: 38 Tom : 99 39 Jack : 80 40 Steaven : 60 41 */