list使用一个doubly linked list(双向链表)来管理元素。
使用list时必须包含头文件<list>
#include <list>
其中list型别定义于namespace std中,是个class template:
namespace std {
template<class T,
class Allocator = allocator<T> >
class list;
}
优缺点:
①list不支持随机存取。
②任何位置上(不只是两端)执行元素的安插和移除都非常快,始终都是常数时间内完成,因为无需移动任何其他元素。(实际只是内部指针操作而已)
③安插和删除动作不会造成指向其他元素的各个pointers、references、iterators失效。
④list对于异常处理有这样的方式:要么操作成功,要么什么都不发生。
list<int> c(c1);
list<int> c;
list<int> c(n,elem);
list<int> c(beg,end);
c.size();
c.empty();
c.max_size();
c1 = c2;
c.assign(c,elem);
c.assign(beg,end);
c1.swap(c2);
swap(c1,c2);//全局函数
c.front();//不检查第一个元素是否存在
c.back();//不检查最后一个元素是否存在
c.begin();
c.end();
c.rbegin();
c.rend();
c.insert(pos,elem);
c.insert(pos,n,elem);
c.insert(pos,beg,end);
c.push_back(elem);
c.pop_back();//移除最后一个元素,但是不回传
c.push_front(elem);
c.pop_front();//移除头部元素,但是不回传
c.remove(val);//移除所有值为val的元素
c.remove_if(op); //移除所有"造成op(elem)结果为true"的元素
c.erase(pos);//移除pos上的元素,返回下一元素的位置
c.erase(beg,end);//移除...,返回下一元素的位置
c.resize(num);//将元素数量改为num
c.resize(num,elem);//将元素数量改为num(如果size()变大了,多出来的新元素都是elem的副本)
c.clear();
///
c.unique();
c.unique(op);
c1.splice(pos,c2);
c1.splice(pos,c2,c2pos);
c1.splice(pos,c2,c2beg,c2end);
c.sort();
c.sort(op);
c1.merge(c2);
c1.merge(c2,op);
c.reverse();//将所有元素反序
应用实例
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
void printLists(const list<int> &list1, const list<int> &list2)
{
cout<<"list1 : ";
copy(list1.begin(), list1.end(), ostream_iterator<int>(cout, " "));
cout<<"list2 : ";
copy(list2.begin(), list2.end(), ostream_iterator<int>(cout, " "));
cout<<endl<<endl;
}
int main(int argc, char **argv)
{
//create two empty lists
list<int> list1, list2;
//fill boths lists with elements
for (int i= 0 ; i < 6; ++ i) {
list1.push_back(i);
list2.push_back(i);
}
printLists(list1, list2);
//move first element to the end
list2.splice(list2.end(), list2, list2.begin());
printLists(list1, list2);
//sort second list, assign to list1 and remove duplicates
list2.sort();
list1 = list2;
list2.unique();
printLists(list1, list2);
//list1 merge with list2
//then list2 is empty
list1.merge(list2);
printLists(list1, list2);
list1.reverse();
printLists(list1, list2);
//filter repeate element, but first we need to sort
list1.unique();
printLists(list1, list2);
return 0;
}
运行结果: