C++基本容器的使用

C++中有queue、list、vector、deque、stack、priority等多個容器,其成員函數的使用比較繁瑣,總結如下

其頭文件分別爲:#include<queue>  #include<list>   #include<vector>  #include<stack> #include<deque>等

這類容器的聲明,是通過將類型放在類模板名稱後面的尖括號中來指定類型:

queue<int> q;

vector<string> svec;

list<char> l;


上述定義中,類型分別爲queue<int> ,vector<string>,list<char>,變量名分別爲:q、svec、l。

還有複雜一些的容器的容器,vector< vector<string> > vec;注意兩個尖括號之間要有空格隔開,否則系統會認作右移操作符,導致編譯錯誤。

這些類定義了好幾種構造函數用來定義和初始化對象。以vector爲例:

vector<T> v1;

vector<T> v2(v1);//v2爲v1的副本

vector<T> v3(n,i);//v3包含n個值爲i的元素

vector<T> v4(n);//v4爲包含n個元素,每個元素爲0

對於queue來說,常用的成員函數如下:push pop size empty front back

逐一舉例說明

1.push 隊列中插入一個元素(由於隊列先進先出,故在隊尾插入)

queue < string > q;

q.push("hello");

q.push("world");

q.push("test");

cout<<q.front()<<endl;

輸出爲 hello

2.front 返回隊列中的第一個元素,上述代碼中的front即爲輸出最先最早進入隊列的元素。

3.pop 將隊列中最先最早位置的元素去除。

queue < string > q;

q.push("hello");

q.push("world");

q.push("test");

q.pop();

cout<<q.front()<<endl;

輸出爲world,最靠前位置的元素hello被去除

4.size 返回隊列中元素的個數,如

queue < string > q;

q.push("hello");

cout<<q.size()<<endl;

q.push("world");

q.push("test");

cout<<q.size()<<endl;

q.pop();

cout<<q.size()<<endl;

輸出爲1 3 2

5.empty 判斷隊列是否爲空,空則返回true,否則返回false

queue < string > q;

cout<<q.empty()<<endl;

q.push("hello");

cout<<q.empty()<<endl;

輸出爲1 0

6.back 返回隊列中最後一個元素

queue < string > q;

q.push("hello");

q.push("world");

q.push("test");

cout<<q.back()<<endl;

輸出爲test

對於vector來說,其成員函數及常規操作如下:

vector的size,和queue類似,如果需要循環vector中的每個元素值,則需要用到size_type,

for(vector<int>::size_type i=0;i!=ivec.size();i++)

除了可以使用size_type,對象元素的下標做容器中元素遍歷,還可以使用迭代器(iterator),具體操作如下:

vector<int>::iterator iter;%迭代器類型定義。使用begin,end來返回迭代器,iter=ivec.begin(),用begin返回的迭代器指向了ivec的第一個元素。

for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)

在迭代器的使用中,只有vector和deque容器支持迭代器的算數運算以及關係操作符,也就是支持iter±n,以及>、<、≥、≤。

其他容器不支持以上兩種情況,它們只能提供前置和後置的自增、自減運算以及相等、不等運算。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章