时间:2021-01-12 13:18:00 | 栏目:C代码 | 点击:次
C++ list的实例详解
Source:
#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:
[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
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!