C++中 STL list詳解及簡單實例
C++中 STL list詳解
1、List: 內(nèi)部實現(xiàn)是一個雙向鏈表,可以高效的進行插入刪除,但不能夠進行隨機訪問
2.、示例程序:
#include "stdafx.h"
#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>
using namespace std;
const int num[5] = {1,3,2,4,5};
bool status(const int & value)
{
return value>6?true:false;
}
int _tmain(int argc, _TCHAR* argv[])
{
list<int> list1;
copy(num,num+5,back_insert_iterator<list<int>>(list1));
copy(list1.begin(),list1.end(),ostream_iterator<int>(cout," "));
cout<<endl;
list1.sort(greater<int>());//5 4 3 2 1
copy(list1.begin(),list1.end(),ostream_iterator<int>(cout," "));
cout<<endl;
list<int>::iterator it = list1.begin();
while (it != list1.end())
{
(*it) += 2;
it++;
}
//7 6 5 4 3
list<int>::reverse_iterator re_it = list1.rbegin();
cout<<"從后向前輸出: ";
while (re_it != list1.rend())
{
cout<<*re_it<<" ";
re_it++;
}
cout<<endl;
list1.reverse();// 3 4 5 6 7
list1.push_back(8);//3 4 5 6 7 8
list1.pop_front();//4 5 6 7 8
list1.remove(6);//4 5 7 8
list1.remove_if(status);// 4 5
list1.resize(4);// 4 5 0 0
list1.resize(6,1);// 4 5 0 0 1 1
list1.unique();//4 5 0 1
copy(list1.begin(),list1.end(),ostream_iterator<int>(cout," "));
cout<<endl;
list1.clear();
cout<<"當前l(fā)ist1含有元素個數(shù):"<<list1.size()<<endl;
list1.push_back(7);//list1:7
list<int> list2(3,2);//2 2 2
list2.merge(list1,greater<int>());//list2: 7 2 2 2
list2.insert(++list2.begin(),3);//list2: 7 3 2 2 2
list2.swap(list1);//list1:7 3 2 2 2 list2:empty
list1.erase(++list1.begin(),list1.end());// 7
copy(list1.begin(),list1.end(),ostream_iterator<int>(cout," "));
cout<<endl;
system("pause");
}
運行結(jié)果圖片:

3、List 方法
|
list成員 |
說明 |
|
constructor |
構(gòu)造函數(shù) |
|
destructor |
析構(gòu)函數(shù) |
|
operator= |
賦值重載運算符 |
|
assign |
分配值 |
|
front |
返回第一個元素的引用 |
|
back |
返回最后一元素的引用 |
|
begin |
返回第一個元素的iterator |
|
end |
返回最后一個元素的下一位置的iterator |
|
rbegin |
返回鏈表最后一元素的后向指針reverse_iterator |
|
rend |
返回鏈表第一元素的下一位置的reverse_iterator |
|
push_back |
增加一個數(shù)據(jù)到鏈表尾 |
|
push_front |
增加一個數(shù)據(jù)到鏈表頭 |
|
pop_back |
刪除鏈表尾的一個元素 |
|
pop_front |
刪除鏈表頭的一元素 |
|
clear |
刪除所有元素 |
|
erase |
刪除一個元素或一個區(qū)域的元素(兩個重載) |
|
remove |
刪除鏈表中匹配值的元素(匹配元素全部刪除) |
|
remove_if |
刪除條件滿足的元素(遍歷一次鏈表),參數(shù)為自定義的回調(diào)函數(shù) |
|
empty |
判斷是否鏈表為空 |
|
max_size |
返回鏈表最大可能長度 |
|
size |
返回鏈表中元素個數(shù) |
|
resize |
重新定義鏈表長度(兩重載函數(shù)) |
|
reverse |
反轉(zhuǎn)鏈表 |
|
sort |
對鏈表排序,默認升序 |
|
merge |
合并兩個有序鏈表并使之有序 |
|
splice |
對兩個鏈表進行結(jié)合(三個重載函數(shù)) 結(jié)合后第二個鏈表清空 |
|
insert |
在指定位置插入一個或多個元素(三個重載函數(shù)) |
|
swap |
交換兩個鏈表(兩個重載) |
|
unique |
刪除相鄰重復(fù)元素 |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C/C++內(nèi)存管理之new與delete的使用及原理解析
這篇文章主要介紹了C/C++內(nèi)存管理之new與delete的使用及原理解析,本文通過實例代碼圖文相結(jié)合給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-08-08

