1. 簡介
set
是 STL的另個一關聯容器,其是關鍵字 key
的簡單集合,無重複元素,底層使用紅黑樹實現,內部元素自動排好序,set元素值爲 const 類型,不能改變。當想要知道一個值是否存在時,set是最有用的。
標準庫提供8個關聯容器:
2. set基本操作
2.1頭文件
#include <set>
2.2 創建set對象
set<int> first; // 定義一個空的set,元素類型爲int
int myints[] = {10,20,30,40,50};
set<int> second (myints, myints+5); // 從myints數組起始位置拷貝5個元素至set
set<int> third (second); // 拷貝初始化,third是second的副本
set<int> fourth (second.begin(), second.end()); // 拷貝迭代器範圍內元素
set<int,classcomp> fifth; // class as Compare
bool(*fn_pt)(int,int) = fncomp;
set<int,bool(*)(int,int)> sixth (fn_pt);
2.3 set元素的訪問
set只存儲key,並且key唯一,所以不能使用下標[ ]訪問,以及at()操作方位,其可以通過迭代器進行訪問。
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main() {
set<string> exclude = {"The", "But", "And", "Or", "An", "A",
"the", "but", "and", "or", "an", "a"};
for (set<string>::iterator iter = exclude.begin(); iter != exclude.end(); iter++) {
cout << *iter << endl;
}
return 0;
}
2.4 set中常用方法
begin() | 返回set容器的第一個元素 |
---|---|
end() | 返回set容器的最後一個元素 |
rbegin() | 返回一個指向set尾部的逆向迭代器 |
rend() | 返回一個指向set頭部的逆向迭代器 |
empty() | 判斷set容器是否爲空 |
size() | 返回set()容器大小 |
max_size() | 返回set容器可能包含的元素最大個數 |
insert() | 插入元素 |
erase() | 刪除元素 |
swap() | 交換兩個set容器:first.swap(second); |
clear() | 清空set容器 |
find(key) | 返回待查找值key的迭代器,若不存在,返回 .end()迭代器 |
count(key) | 返回關鍵字key出現的次數 |
lower_bound(key) | 返回第一個 >= key的迭代器 |
upper_bound(key) | 返回第一個 > key的迭代器 |
equal_range(key) | 返回一個迭代器pair<iterator, iterator> ,表示關鍵字 == key的元素範圍。若key不存在,pair的兩個迭代器均等於 .end() |
具體每個函數的使用細節可以參考 map 的方法,都是類似的。