c++ list
1.关于list容器
list是一种序列式容器。list容器完成的功能实际上和数据结构中的双向链表是极其相似的,list中的数据元素是通过链表指针串连成逻辑意义上的线性表,也就是list也具有链表的主要优点,即:在链表的任一位置进行元素的插入、删除操作都是快速的。list的实现大概是这样的:list的每个节点有三个域:前驱元素指针域、数据域和后继元素指针域。前驱元素指针域保存了前驱元素的首地址;数据域则是本节点的数据;后继元素指针域则保存了后继元素的首地址。其实,list和循环链表也有相似的地方,即:头节点的前驱元素指针域保存的是链表中尾元素的首地址,list的尾节点的后继元素指针域则保存了头节点的首地址,这样,list实际上就构成了一个双向循环链。由于list元素节点并不要求在一段连续的内存中,显然在list中是不支持快速随机存取的,因此对于迭代器,只能通过“++”或“--”操作将迭代器移动到后继/前驱节点元素处。而不能对迭代器进行+n或-n的操作,这点,是与vector等不同的地方。
2.list中常用的函数
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; }
结果