C++ List的用法(整理)
C++ List的用法(整理)
資料來源: https://blog.csdn.net/lskyne/article/details/10418823
純C++線上編譯測試: https://www.tutorialspoint.com/compile_cpp_online.php
純C 線上編譯測試: https://www.tutorialspoint.com/compile_c_online.php
List將元素按順序儲存在鍊錶中. 與向量(vectors)相比, 它允許快速的插入和刪除,但是隨機訪問卻比較慢.
常用成員列表:
assign()給list賦值
back()返回最後一個元素
begin()返回指向第一個元素的迭代器
clear()刪除所有元素
empty()如果list是空的則返回true
end()返回末尾的迭代器
erase()刪除一個元素
front()返回第一個元素
get_allocator()返回list的配置器
insert()插入一個元素到list中
max_size()返回list能容納的最大元素數量
merge()合併兩個list
pop_back ()刪除最後一個元素
pop_front()刪除第一個元素
push_back()在list的末尾添加一個元素
push_front()在list的頭部添加一個元素
rbegin()返回指向第一個元素的逆向迭代器
remove( )從list刪除元素
remove_if()按指定條件刪除元素
rend()指向list末尾的逆向迭代器
resize()改變list的大小
reverse()把list的元素倒轉
size()返回list中的元素個數
sort( )給list排序
splice()合併兩個list
swap()交換兩個list
unique()刪除list中重複的元素
範例:
#include <iostream>
#include <list>
#include <numeric>
#include <algorithm>
using namespace std;
//创建一个list容器的实例LISTINT
typedef list<int> LISTINT;
//创建一个list容器的实例LISTCHAR
typedef list<int> LISTCHAR;
int main()
{
//用list容器处理整型数据
//用LISTINT创建一个名为listOne的list对象
LISTINT listOne;
//声明i为迭代器
LISTINT::iterator i;
//从前面向listOne容器中添加数据
listOne.push_front (2);
listOne.push_front (1);
//从后面向listOne容器中添加数据
listOne.push_back (3);
listOne.push_back (4);
//从前向后显示listOne中的数据
cout<<"listOne.begin()--- listOne.end():"<<endl;
for (i = listOne.begin(); i != listOne.end(); ++i)
cout << *i << " ";
cout << endl;
//从后向后显示listOne中的数据
LISTINT::reverse_iterator ir;
cout<<"listOne.rbegin()---listOne.rend():"<<endl;
for (ir =listOne.rbegin(); ir!=listOne.rend();ir++) {
cout << *ir << " ";
}
cout << endl;
//使用STL的accumulate(累加)算法
int result = accumulate(listOne.begin(), listOne.end(),0);
cout<<"Sum="<<result<<endl;
cout<<"------------------"<<endl;
//--------------------------
//用list容器处理字符型数据
//--------------------------
//用LISTCHAR创建一个名为listOne的list对象
LISTCHAR listTwo;
//声明i为迭代器
LISTCHAR::iterator j;
//从前面向listTwo容器中添加数据
listTwo.push_front ('A');
listTwo.push_front ('B');
//从后面向listTwo容器中添加数据
listTwo.push_back ('x');
listTwo.push_back ('y');
//从前向后显示listTwo中的数据
cout<<"listTwo.begin()---listTwo.end():"<<endl;
for (j = listTwo.begin(); j != listTwo.end(); ++j)
cout << char(*j) << " ";
cout << endl;
//使用STL的max_element算法求listTwo中的最大元素并显示
j=max_element(listTwo.begin(),listTwo.end());
cout << "The maximum element in listTwo is: "<<char(*j)<<endl;
return 0;
}
/*
結果
listOne.begin()--- listOne.end():
1 2 3 4
listOne.rbegin()---listOne.rend():
4 3 2 1
Sum=10
------------------
listTwo.begin()---listTwo.end():
B A x y
The maximum element in listTwo is: y
*/