list双向链表容器(常用的方法总结)

  特别注意,由于list对象的结点并不要求在一段连续的内存中,所以,对于迭代器,只能通过++或者--的操作将迭代器移动到后继或者前驱结点元素处。而不能对迭代器进行+n或者-n的操作,
这点与vector等不同的地方。

  

 1 /*关于C++STL中的list双向链表容器的学习。*/
 2 #include <list>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 void print(list<int> l);
 7 void rprint(list<int> l);
 8 
 9 int main()
10 {
11     //创建list对象
12     list<int> l;
13     
14     //插入元素的三种方式
15     l.push_back(2);//向尾部插入元素,链表自动扩张
16     l.push_front(1);//向首部插入元素,链表自动扩张
17     
18     //在链表中间插入新的元素
19     list<int>::iterator it;
20     it=l.begin();
21     it++;//只能++或者--
22     l.insert(it,4);
23     cout<<"正向遍历:
";
24     print(l); 
25     cout<<"方向遍历:
";
26     rprint(l);
27     
28     
29     //元素的删除
30     //值得特别注意的是如果想要删除该链表中所有键值为某值得元素时,使用remove()方法
31     l.push_back(1);
32     l.push_back(3); 
33      l.push_back(5);
34      cout<<"删除前:
"; 
35      print(l);
36      l.remove(1);
37      cout<<"删除后:
";
38      print(l);
39      
40      //删除链表首元素和尾元素
41      cout<<"删除前:
";    
42      print(l);
43     l.pop_front(); 
44     l.pop_back();
45     cout<<"删除后:
";
46     print(l);
47     //此外还可以使用erase()方法和clear()方法
48     
49     //元素的查找find()
50     
51     l.push_back(1);
52     l.push_back(3); 
53      l.push_back(5);
54     //元素的排序
55     cout<<"排序前:
";
56     print(l);
57     l.sort();//默认从小到大排序
58     cout<<"排序后: 
";
59     print(l);
60     //自定义排序分为结构体和非结构体 
61      
62     //另外如果想要提出连续重复的元素则使用unique()方法 
63     return 0;
64 }
65 
66 void print(list<int> l)
67 {
68     //使用前向迭代器遍历链表
69     list<int>::iterator it;
70     for(it=l.begin(); it != l.end(); it++){
71         cout<<(*it)<<endl; 
72     } 
73 }
74 
75 void rprint(list<int> l)
76 {
77     list<int>::reverse_iterator rit;
78     for(rit = l.rbegin(); rit != l.rend(); rit++){
79         cout<<(*rit)<<endl;
80     }
81 }
原文地址:https://www.cnblogs.com/wenzhixin/p/8529987.html