STL list

list简介

  • #inlude < list >
  • 实质为双向链表
  • 是类模板

 

实例化

example:

 1 //instantiate an empty list
 2 list<int> listA;
 3 
 4 //instantiate a list with 7 intergers,each initialized to 0
 5 list<int> listB(7);
 6 
 7 //instantiate a list with 7 intergers,each initialized to 1
 8 list<int> listC(7,1);
 9 
10 // an copy of an existing list
11 list<int> listD(listC);
12 
13 //a vector with 7 intergers,each 2
14 vector<int> vecA(7,2);
15 
16 //instantiate a list using values from another container
17 list<int> listE(vecA.cbegin(),vecA.cend());
18 
19 int myints[]={1,2,3,4,5,6,7};
20 //instantiate a list  using values form a array
21 list<int> listF(myints,myints+sizeof(myints)/sizeof(int));

 

 

result:

1                      
2 0 0 0 0 0 0 0 
3 1 1 1 1 1 1 1 
4 1 1 1 1 1 1 1 
5 2 2 2 2 2 2 2 
6 1 2 3 4 5 6 7

 

 


插入元素

 1 //insert elements at the beginning
 2 listA.pushfront(2);
 3 
 4 //inserting elements at the end
 5 listA.pushback(3);
 6 
 7 //insert elements at the beginning
 8 listA.insert(listA.begin(),1);
 9 
10 //insert 7 elements of the same value 2
11 listA.insert(listA.begin(),7,2);
12 
13 //insert elements fron another list at the begining
14 listA.insert(listA.begin(),listF.begin(),listF.end());

 

 

删除元素

1 //接受一个迭代器参数并删除迭代器指向的元素
2 listA.erase(iterator)
3 //接受两个迭代器参数并删除指定范围内的所有元素
4 listA.erase(listA.begin(),listA.end());

 


反转

//该函数没有参数,它反转list中元素的排列顺序
listA.reverse();

 


排序

//没有参数,采用升序排列
listA.sort();
//二元谓词作为参数,指定排序标准
bool Descending(const int& lsh,const int& rsh)
{
      return(lsh>rsh)
}

listA.sort(Descending);

 

 


清空

1 listA.clear();

是否为空

1 //原型
2 bool empty();
3 //使用
4 listA.empty();

元素个数

1 //原型,返回容器内元素个数
2 unsigned int size() const;
3 //使用
4 listA.size()

forward_list简介

  • #include <forward_list>
  • 单向链表,不能使用push_back
  • 只允许沿一个方向遍历

 

posted @ 2014-04-15 13:23  猫了个妖喵  阅读(125)  评论(0编辑  收藏  举报