Fork me on GitHub

STL——容器(List)list 的反序排列

list.reverse();

//反转链表,比如list包含1, 2, 3, 4, 5五个元素,运行此方法后,list就包含5, 4, 3, 2, 1元素。

 1 #include <iostream>
 2 #include <list>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int num[] = { 1,2,3,4,5 };
 9     list<int> listInt(num, num + size(num));
10     cout << "反序前遍历 listInt:";
11     for (list<int>::iterator it = listInt.begin(); it != listInt.end(); it++)
12     {
13         cout << *it << " ";
14     }
15     cout << endl;
16 
17     listInt.reverse();
18 
19     cout << "反序后遍历 listInt:";
20     for (list<int>::iterator it = listInt.begin(); it != listInt.end(); it++)
21     {
22         cout << *it << " ";
23     }
24 
25     return 0;
26 }

打印结果:

 

 

list.sort();

//整数排序,只可以排序整数与浮点数,不可以排序字符

 1 #include <iostream>
 2 #include <list>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int num[] = { 5,6,3,2,1,4 };
 9     list<int> listInt(num, num + size(num));
10     cout << "排列前遍历 listInt:";
11     for (list<int>::iterator it = listInt.begin(); it != listInt.end(); it++)
12     {
13         cout << *it << " ";
14     }
15     cout << endl;
16 
17     listInt.sort();
18 
19     cout << "排列前遍历 listInt:";
20     for (list<int>::iterator it = listInt.begin(); it != listInt.end(); it++)
21     {
22         cout << *it << " ";
23     }
24     cout << endl;
25 
26     float num_1[] = { 1.5,1.2,1.6,1.7,1.1 };
27     list<float> listFloat(num_1, num_1 + size(num_1));
28     cout << "排列前遍历 listFloat:";
29     for (list<float>::iterator fl = listFloat.begin(); fl != listFloat.end(); fl++)
30     {
31         cout << *fl << " ";
32     }
33     cout << endl;
34 
35     listFloat.sort();
36 
37     cout << "排列前遍历 listInt:";
38     for (list<float>::iterator fl = listFloat.begin(); fl != listFloat.end(); fl++)
39     {
40         cout << *fl << " ";
41     }
42     cout << endl;
43 
44     return 0;
45 }

打印结果:

 

 

 

 

 

 

 

 

 

 

 

 

====================================================================================================================

posted @ 2020-05-05 17:31  索智源  阅读(529)  评论(0编辑  收藏  举报