list模板
1.list模板表示双向链表,除了第一个和最后一个元素外,每个元素都与前后的元素相连接,这意味着可以双向遍历链表
2.list是可反转容器
3.list容器不支持数组表示法和随机访问
一、list成员函数
1.void merage(list<T,Alloc> & x)
//将链表x与调用链表合并,两个链表必须已经排序。合并后的经过排序的链表保存在调用链表中,x为空。
2.void remove(const T & val)
//从链表中删除所有的val。
3.void sort()
//使用<运算符对链表进行排序:N个元素的复杂度为NlogN
4.void splice(iterator pos,lis<T,Alloc> x)
//将链表x的内容插入到pos的前面,x将为空,复杂度为固定时间
5.void unique()
//将连续的相同元素压缩为单个元素,复杂度为线性时间
demon
#include<iostream>
#include<list>
#include<iterator>
#include<algorithm>
void outint(int n) { std::cout << n << " "; }
int main()
{
using namespace std;
list<int> one(5,2);
int stuff[5] = {1,2,4,8,6};
list<int> two;
two.insert(two.begin(),stuff,stuff + 5);//insert方法将原始区间副本插入
int more[6] = {6,4,2,4,6,5};
list<int> three(two);
three.insert(three.end(),more,more+6);
cout << "初始:\n" <<"List one : ";
for_each(one.begin(),one.end(),outint);
cout << endl << "List two:";
for_each(two.begin(),two.end(),outint);
cout << endl << "List three:";
for_each(three.begin(),three.end(),outint);
cout << "\n变化:" ;
three.remove(2);
cout << endl << "List three 删除元素2后: ";
for_each(three.begin(),three.end(),outint);
three.splice(three.begin(),one);//splice方法是将原始区间移到目标地址
cout<< endl << "List three after splice: ";
for_each(three.begin(),three.end(),outint);
cout<< endl << "List one: ";
for_each(one.begin(),one.end(),outint);
three.unique();//将相邻的相同值压缩为单个值
cout << endl << endl << "List three after unique:";
for_each(three.begin(),three.end(),outint);
three.sort();//排序
three.unique();//将相邻的相同值压缩为单个值
cout << endl << "List three after sort & unique: ";
for_each(three.begin(),three.end(),outint);
cout << endl;
two.sort();
three.merge(two);//归并排序算法
cout << endl << "Sorted two merged into three: ";
for_each(three.begin(),three.end(),outint);
cout << endl << "List two:";
for_each(two.begin(),two.end(),outint);
cout << endl;
return 0;
}
运行结果: