C 學習紀錄 vector容器 容量與大小

2021-10-08 14:58:51 字數 2579 閱讀 9806

1、empty()判斷容器是否為空。為空返回真,不為空返回假。

2、capacity()返回容器的容量

3、size()返回容器中元素的個數。元素個數不一定等於容器容量。

4、resize(int num)重新指定容器的長度為num。若容器變長,以預設值0填充新位置。如果容器變短,則末尾超出容器長度的元素被刪除。

5、resize(int num, elem)重新指定容器的長度為num。若容器變長,以elem值填充新位置。如果容器變短,則末尾超出容器長度的元素被刪除。

一、empty()判斷容器是否為空。為空返回真,不為空返回假。

#include

using

namespace std;

#include

intmain()

else

system

("pause");

}

執行結果:

vector is empty

請按任意鍵繼續.

..

二、capacity()和size()

#include

using

namespace std;

#include

intmain()

cout <<

"the capacity of vector is "

<< v.

capacity()

<< endl;

cout <<

"the size of vector is "

<< v.

size()

<< endl;

system

("pause");

}

執行結果:

the capacity of vector is 8

the size of vector is 5

請按任意鍵繼續.

..

會發現,尾插法存入資料時,容器的capacity會大於size。

三、**resize()**重新指定容器的長度為num

#include

using

namespace std;

#include

void

printvector

(vector<

int>

&v) cout << endl;

}int

main()

cout <<

"the capacity of vector is "

<< v.

capacity()

<< endl;

cout <<

"the size of vector is "

<< v.

size()

<< endl;

printvector

(v);

cout << endl;

//重新指定大小,該大小大於原容器容量,新位置用10填充

v.resize(10

,100);

cout <<

"the capacity of vector is "

<< v.

capacity()

<< endl;

cout <<

"the size of vector is "

<< v.

size()

<< endl;

printvector

(v);

cout << endl;

//重新指定大小,該大小小於原容量大小

v.resize(2

);cout <<

"the capacity of vector is "

<< v.

capacity()

<< endl;

cout <<

"the size of vector is "

<< v.

size()

<< endl;

printvector

(v);

system

("pause");

}

執行結果:

the capacity of vector is 8

the size of vector is 512

345the capacity of vector is 10

the size of vector is 1012

345100

100100

100100

the capacity of vector is 10

the size of vector is 212

請按任意鍵繼續.

..

C 學習紀錄 vector容器 插入和刪除

1 push back elem 尾部插入元素elem 2 pop back 刪除最後乙個元素 3 insert const iterator pos,elem 向迭代器指向的位置插入elem 4 insert const iterator pos,int count,elem 向迭代器指向位置插入...

C 學習紀錄 string容器 查詢

1 int find const string str,int pos 0 const查詢str第一次出現位置,從pos開始查詢 2 int find const char s,int pos 0 const 查詢s第一次出現位置,從pos開始查詢 3 int find const char s,i...

vector容器容量自動增長的原理

1.vector會自己根據資料的大小進行容量增長。檢視vector容量增長的次數 int count 0 int p null vectorv for int i 0 i 100000 i cout count count endl cout 容量 v.capacity endl cout 大小 v...