STL序列式容器之list

2022-04-15 17:01:20 字數 3920 閱讀 3215

一,list容器基本概念

1.list容器基本知識

二,list容器建構函式

1.無參建構函式

//

無參建構函式

list l1;

2.有參建構函式

//

有參建構函式,10個字元'a'來初始化容器

list l2(10, 'a'

);//

有參建構函式,用上面的容器初始化下面的容器

list l3(l2.begin(), l2.end());

3.拷貝建構函式

//

有參建構函式

list l1(10, 'a'

);//

拷貝建構函式

list l2 = l1;

4.析構函式

list的析構函式用來釋放容器中元素所占用的記憶體。

三,list容器的操作符過載

1.賦值操作符

//

定義鍊錶容器l1

list l1(10, "

helloworld");

//定義鍊錶容器l2

listl2;

//賦值操作符過載

l2 = l1;

四,list容器的成員函式

1.頭部插入和刪除元素

//

定義容器

listl1;

//在容器頭部新增元素

l1.push_front("

hello");

l1.push_front(

"world");

l1.push_front(

"c++");

//移除容器頭部元素

l1.pop_front();

2.尾部插入和刪除元素

//

定義容器

listl1;

//在容器尾部新增元素

l1.push_back("

oracle");

l1.push_back(

"ibm");

l1.push_back(

"microsoft");

//移除容器尾部元素

l1.pop_back();

3.容器的頭部和尾部元素

//

定義容器

listl1;

//在容器頭部新增元素

l1.push_front("

hello");

l1.push_front(

"world");

l1.push_front(

"c++");

//獲取容器的頭部和尾部元素

string first =l1.front();

string last = l1.back();

4.容器的大小

//

定義容器

listl1;

//在容器頭部新增元素

l1.push_front("

hello");

l1.push_front(

"world");

l1.push_front(

"c++");

//獲取容器的大小

int size = l1.size();

5.容器的清空

//

定義容器

list l1(10,"

helloworld");

//容器的清空

l1.clear();

6.容器是否為空

//

定義容器

list l1(10,"

helloworld");

//容器是否為空

bool isempty = l1.empty();

7.容器的插入元素

//

定義容器l2

list l2(5, "

helloworld");

//在容器第二個位置插入"helloc++",list只支援++和--,不支援具體的加幾和減幾,因為底層是鍊錶

l2.insert(++l2.begin(), "

helloc++");

//基於list容器的特徵,經常配合迭代器來插入

for (list::iterator it = l2.begin(); it != l2.end(); it++)

8.容器的刪除元素

//

定義容器l2

list l2(5, "

helloworld");

//刪除容器的所有元素

l2.erase(l2.begin(), l2.end());

//根據容器元素的值刪除

l2.remove("

helloc++

");

9.容器的遍歷

//

定義容器

list l2(10,"

helloworld");

//增強for遍歷

for (string

tmp : l2)

cout

for (list::iterator it = l2.begin(); it != l2.end(); it++)

cout

for (list::reverse_iterator it = l2.rbegin(); it != l2.rend(); it++)

cout

<< endl;

10.容器的反轉

//

定義容器

listl1;

//在容器頭部新增元素

l1.push_front("

hello");

l1.push_front(

"world");

l1.push_front(

"c++");

//容器的反轉

l1.reverse();

11.list的遍歷刪除

# include# include

using

namespace

std;

intmain()

else

}//遍歷

for (int

tmp : v)

cout

}

五,list容器注意事項

1.儲存自定義資料型別的注意

要儲存的自定義型別必須提供拷貝建構函式,因為容器是通過值的複製方式將元素存入到容器中的。

2.list容器的訪問

list容器不支援隨機訪問元素,即不支援索引下標的方式訪問和修改元素,要想訪問元素必須通過迭代器進行遍歷,遍歷到要找到的位置。

3.list容器的迭代器

STL序列式容器之list(雙向鍊錶)

和vector相比,list的實現更加複雜,因為它並不要求空間是連續儲存的,它的好處是已知位置的元素插入和移除都是常數時間。1 list的節點 由於list是雙向鍊錶,因此list的節點需要指向前驅節點的指標以及指向後繼節點的指標。2 list的迭代器 由於空間並不連續,因此list無法支援隨機訪問...

STL學習筆記 序列式容器list

由於vector的使用,經常會出現迭代器錯誤,主要是因為vector在每次更改完資料就會重新配置,迭代器就會失效,list的結構和vector的設計差異決定了list在這方面具有優越性,list的insert和splice操作不會造成迭代器失效,並且erase也只會是讓當前元素的迭代器失效。list...

STL 序列式容器 list(簡單複習)

stl 常用容器總結,帶有複習性質的學習更有效率 list 和 vector 是最常用的兩個容器,也是在面試中最常被問到的,讓你對比一下這兩個容器 那麼,首先複習一下 list 的結構,list 底層的資料結構是雙向鍊錶,同時,和vector不同的是,list 的迭代器不再是原生指標,而是專門封裝的...