C STL庫中set的常見操作

2021-10-02 13:33:27 字數 2634 閱讀 1063

#include

#include

using namespace std;

set <

int> s;

注意:

有序性。set容器中的元素預設公升序排序;

重複性。set容器中沒有重複的元素。

1.迭代器

s.

begin()

;//返回指向容器頭部的迭代器

s.end()

;//返回指向容器尾部的迭代器

s.rbegin()

;//等價於s.end()

s.rend()

;//等價於s.begin()

2.插入操作

插入格式:

s.insert(i); //直接向容器中新增i元素

s.insert(first,second);//插入區間(first,second)的中的元素

該區間為左閉右開區間

#include

#include

using namespace std;

intmain()

以上**的運算結果如下:

3.刪除操作

格式:

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

s.erase(pos);//刪除位置為pos的元素

s.erase(s.begin(),s.end());//刪除所有元素。等價於s.clear()。

#include

#include

using namespace std;

intmain()

; set <

int> s (a,a+5)

;//陣列a中的元素全部賦給s

s.erase(3

);//第一種刪除方式,刪除元素3

for(set <

int>

::iterator it = s.

begin()

;it != s.

end(

);it++

) cout<

//運算結果:1 2 4 5

s.erase

(s.begin()

);//第二種刪除方式,刪除第乙個元素

for(set <

int>

::iterator it = s.

begin()

;it != s.

end(

);it++

) cout<

//運算結果:2 4 5

s.erase

(s.begin()

,s.end()

);//第三種刪除方式,刪除所有元素

if(s.

empty()

) cout<<

"set為空!!!"

;//運算結果:set為空!!!

return0;

}

以上**執行結果如下:

4.其他常見函式

s.

size()

;//返回當前容器中的元素個數

s.max_size()

;//返回set容器的最大容量

s.count()

;//判斷某元素的出現次數。因為在set中沒有重複出現的元素,所以該函式只判斷該元素是否存在

s.swap()

;//交換兩個set容器中的所有元素

#include

#include

using namespace std;

intmain()

for(

int j =

4;j<=

8;j++

) cout<

size()

<

//運算結果:6

cout<

max_size()

<

s1.swap

(s2)

; set <

int>

::iterator it=s1.

begin()

;while

(it != s1.

end())

//運算結果:4 5 6 7 8

return0;

}

以上**執行結果如下:

C STL中的容器 Set

set跟vector差不多,它跟vector的唯一區別就是,set裡面的元素是有序的且唯一的,只要你往set裡新增元素,它就會自動排序,而且,如果你新增的元素set裡面本來就存在,那麼這次新增操作就不執行。要想用set先加個頭檔案set。其中數值型按照從小到大排列 字元型按照字典序排列 includ...

C STL中set的常用方法

set模板類在標頭檔案 中使用前需要先引入標頭檔案。set集合容器實現了紅黑樹 red black tree 的平衡二叉檢索樹的資料結構,在插入元素時,它會自動調整二叉樹的排列,把該元素放到適當的位置,以確保每個樹根節點的鍵值大於左子樹所有節點的鍵值,而小於右子樹所有節點的鍵值 另外,還確保根節點左...

C STL中set和multiset的使用方法

構造 set集合主要目的是為了快速檢索,不可直接去修改鍵值。需要引用標頭檔案 include template classcompare less,classalloc stl default allocator key 比較函式物件及記憶體分配器採用的是預設引數,因此如果未指定,它們將採用系統預設...