Source:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#include <iostream> #include <list> #include <numeric> #include <algorithm> using namespace std; typedef list< int > LISTINT; //创建一个list容器的实例LISTINT typedef list< int > LISTCHAR; //创建一个list容器的实例LISTCHAR int main( void ) { LISTINT listOne; //用LISTINT创建一个名为listOne的list对象 LISTINT::iterator i; //声明i为迭代器 listOne.push_front (2); //从前面向listOne容器中添加数据 listOne.push_front (1); listOne.push_back (3); //从后面向listOne容器中添加数据 listOne.push_back (4); cout<< "listOne.begin()--- listOne.end():" <<endl; //从前向后显示listOne中的数据 for (i = listOne.begin(); i != listOne.end(); ++i) cout << *i << " " ; cout << endl; LISTINT::reverse_iterator ir; //从后向后显示listOne中的数据 cout<< "listOne.rbegin()---listOne.rend():" <<endl; for (ir =listOne.rbegin(); ir!=listOne.rend();ir++) cout << *ir << " " ; cout << endl; int result = accumulate(listOne.begin(), listOne.end(),0); //使用STL的accumulate(累加)算法 cout<< "Sum=" <<result<<endl; LISTCHAR listTwo; //用LISTCHAR创建一个名为listOne的list对象 LISTCHAR::iterator j; //声明j为迭代器 listTwo.push_front ( 'A' ); //从前面向listTwo容器中添加数据 listTwo.push_front ( 'B' ); listTwo.push_back ( 'x' ); //从后面向listTwo容器中添加数据 listTwo.push_back ( 'y' ); cout<< "listTwo.begin()---listTwo.end():" <<endl; //从前向后显示listTwo中的数据 for (j = listTwo.begin(); j != listTwo.end(); ++j) cout << char (*j) << " " ; cout << endl; //使用STL的max_element算法求listTwo中的最大元素并显示 j=max_element(listTwo.begin(),listTwo.end()); cout << "The maximum element in listTwo is: " << char (*j)<<endl; return 0; } |
Result:
1
2
3
4
5
6
7
8
9
10
|
[work @db -testing-com06-vm3.db01.baidu.com c++]$ g++ -o list list.cpp [work @db -testing-com06-vm3.db01.baidu.com c++]$ ./list listOne.begin()--- listOne.end(): 1 2 3 4 listOne.rbegin()---listOne.rend(): 4 3 2 1 Sum= 10 listTwo.begin()---listTwo.end(): B A x y The maximum element in listTwo is: y |
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/ithomer/article/details/5997607