set集合容器:
調用頭文件:
- #include<set>
- using namespace std;
詳細用法(部分):
- set<int> t ------ 定義一個int類型的容器,(默認)裏面元素從小到大
- set<int, greater<int> > t ------ 定義一個int類型的容器,裏面元素從大到小
- t.insert(k) ------ 插入元素k,多次插入同一個元素後面無效
- t.count(k) ------ 判斷元素k是否在容器內
- t.erase(k) ------ 刪除元素k,若不存在則刪除無效
- t.clear() ------ 清空容器
- t.size() ------ 返回容器現有元素個數
- t.empty() ------ 判斷容器是否爲空
想遍歷set裏的元素或進行進一步修改,必須定義對應迭代器,以下三種定義方法(迭代器類似於指針)
- set<int>::iterator it ------ 定義正向迭代器
- set<int>::reverse_iterator rit; ------ 定義反向迭代器
- auto it = t.begin(); ------ 因t.begin()返回正向迭代器,所以it自動被定義爲正向迭代器,可適應其他所有操作
以下需要迭代器的操作:
- t.begin() ------ 返回set中第一個元素,類型爲正向迭代器
- t.rbegin() ------ 返回set中最後一個元素的後面一個位置,類型爲反向迭代器
- t.end() ------ 返回set中最後一個元素,類型爲正向迭代器
- t.rend() ------ 返回set中第一個元素,類型爲反向迭代器
- t.find(k) ------ 尋找k,若找到返回對應的迭代器,否則返回end();
- t.insert(a, b) ------ 插入指針[a, b)之間的元素,已有元素不會再次插入
- t.erase(it) ------ 刪除迭代器it對應的元素
- t.erase(l, r) ------ 刪除迭代器[l, r)之間的元素
- lower_bound(k) ------ 返回第一個大於等於k的元素的迭代器
- upper_bound(k) ------ 返回第一個大於k的元素的迭代器
- #include<stdio.h>
- #include<set>
- using namespace std;
- set<int> t;
- int main(void)
- {
- t.insert(5);
- t.insert(3);
- t.insert(8);
- t.insert(9);
- t.insert(12);
- printf("the size is %d\n", t.size());
- printf("%d %d\n", t.count(5), t.count(-1)); //運行結果:1 0
-
- set<int>::iterator it;
- for(it=t.begin();it!=t.end();it++) //運行結果:3 5 8 9 12
- printf("%d ", *it);
- printf("\n");
-
- set<int>::reverse_iterator rit;
- for(rit=t.rbegin();rit!=t.rend();rit++) //運行結果:12 9 8 5 3
- printf("%d ", *rit);
- printf("\n");
-
- auto a = t.begin();
- auto b = t.begin();
- b++;
- t.erase(a,b);
- for(it=t.begin();it!=t.end();it++) //運行結果:5 8 9 12
- printf("%d ", *it);
- printf("\n");
-
- a = t.lower_bound(6);
- b = t.upper_bound(8);
- printf("%d %d\n", *a, *b); //運行結果:8 9
- return 0;
- }