STL封裝之multiset 超全整理

2021-10-23 04:28:52 字數 2911 閱讀 8752

multiset內部的原理是用平衡二叉樹實現,因此無論是查詢還是刪除操作,時間複雜度都比較低,給我們很大的遍歷。

標頭檔案:set

#include

容器命名:multiset《資料型別》容器名稱

操作集:

1.插入,刪除

multiset<

int> ms;

ms.insert(7

);//插入元素7

ms.insert(10

);ms.

insert(5

);cout <<

"ms contains:"

;while

(!ms.

empty()

)//empty判斷容器ms是不是為空

//ms contains: 5 7 10

ms.erase

(first, last)

;//刪除容器中在區間[first, last)中的元素

ms.erase

(pos)

;//刪除容器中第pos個元素

2.查詢

ms.

find

(值);

//在容器中找到某乙個值,找到了返回位址,找不到,返回容器末位置

for(

int i=

1; i<=

5; i++

) ms.

insert

(i *10)

;// 10 20 30 40 50

it=ms.

find(50

);//找到的是元素位址

cout<<

"the value of position it is:"

<<

*it

ms.erase (it)

;//刪除位置為it的元素

ms.erase (ms.

find(40

)); cout <<

"ms contains:"

;for

(it = ms.

begin()

; it != ms.

end(

); it++

) cout <<

' '<<

*it;

//ms contains: 10 20 30

3.判斷容器是都為空,容器大小,起始終止位置

ms.

empty()

;//容器為空,返回true,否則返回false

ms.size()

;//返回容器大小

ms.clear()

;//清除容器

ms.begin()

;//返回容器的起始位置

ms.end();

//返回容器的結束位置

4.計算某乙個元素出現的次數

int myints=

;//數某乙個數出現的次數

multiset<

int> ms (myints,myints +6)

; cout <<

<< ms.

count(73

)<<

" times in ms.\n"

; cout <<

<< ms.

count(12

)<<

" times in ms.\n"

;

5.輸出容器中的所有元素

for

(multiset<

int>

::iterator it = ms.

begin()

; it != ms.

end(

); it++

) cout <<

*it<<

" ";

6.swap函式

int myints3=

; multiset<

int>

first

(myints3, myints3 +3)

;// 4,19,72

multiset<

int>

second

(myints3 +

3, myints3 +6)

;// 20,20,36

first.

swap

(second)

; cout <<

"first contains:"

;for

(multiset<

int>

::iterator it = first.

begin()

; it != first.

end(

); it++

) cout <<

*it<<

" ";

cout <<

"\nsecond contains:"

;for

(multiset<

int>

::iterator it = second.

begin()

; it != second.

end(

); it++

) cout <<

*it<<

" ";

//first contains:4 5 6

//second contains:1 2 3

STL之set和multiset總結

set c 建立空集合,不包含任何元素 set c op 以op為排序準則,產生乙個空的set set c1 c2 複製c2中的元素到c1中 set c const value type first,const value type last 複製 first,last 之間元素構成新集合 set ...

STL詳解之set和multiset

set 裡面的元素不能重複,自動排序 multiset 裡面的元素自動排序,可以有重複的。include using namespace std include include void f1 不取最後一位的反斜槓0 vectorvec ia,ia 10 setiset vec.begin vec....

STL常用操作 multiset

multisetset1 建立空set multisetset2 set1 拷貝構造 multisetset3 set1.begin set1.end 迭代器構造 multisetset4 arr,arr 5 陣列構造 multisetset5 move set2 移動構造 multisetset6...