C++ list的實例詳解
更新時間:2017年09月29日 09:13:25 作者:陽光島主
這篇文章主要介紹了 C++ list的實例詳解的相關(guān)資料,希望通過本文大家能夠理解掌握這部分內(nèi)容,需要的朋友可以參考下
C++ list的實例詳解
Source:
#include <iostream>
#include <list>
#include <numeric>
#include <algorithm>
using namespace std;
typedef list<int> LISTINT; //創(chuàng)建一個list容器的實例LISTINT
typedef list<int> LISTCHAR; //創(chuàng)建一個list容器的實例LISTCHAR
int main(void) {
LISTINT listOne; //用LISTINT創(chuàng)建一個名為listOne的list對象
LISTINT::iterator i; //聲明i為迭代器
listOne.push_front (2); //從前面向listOne容器中添加數(shù)據(jù)
listOne.push_front (1);
listOne.push_back (3); //從后面向listOne容器中添加數(shù)據(jù)
listOne.push_back (4);
cout<<"listOne.begin()--- listOne.end():"<<endl; //從前向后顯示listOne中的數(shù)據(jù)
for (i = listOne.begin(); i != listOne.end(); ++i)
cout << *i << " ";
cout << endl;
LISTINT::reverse_iterator ir; //從后向后顯示listOne中的數(shù)據(jù)
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創(chuàng)建一個名為listOne的list對象
LISTCHAR::iterator j; //聲明j為迭代器
listTwo.push_front ('A'); //從前面向listTwo容器中添加數(shù)據(jù)
listTwo.push_front ('B');
listTwo.push_back ('x'); //從后面向listTwo容器中添加數(shù)據(jù)
listTwo.push_back ('y');
cout<<"listTwo.begin()---listTwo.end():"<<endl; //從前向后顯示listTwo中的數(shù)據(jù)
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
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
詳解C語言的exp()函數(shù)和ldexp()函數(shù)以及frexp()函數(shù)
這篇文章主要介紹了詳解C語言的exp()函數(shù)和ldexp()函數(shù)以及frexp()函數(shù),注意這三個函數(shù)雖然看起來相似但實際功能卻大相徑庭!需要的朋友可以參考下
2015-08-08
C++標(biāo)準(zhǔn)模板庫vector的常用操作
今天小編就為大家分享一篇關(guān)于C++標(biāo)準(zhǔn)模板庫vector的常用操作,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
2018-12-12
淺談CMake配置OpenCV 時靜態(tài)鏈接與動態(tài)鏈接的選擇
下面小編就為大家?guī)硪黄獪\談CMake配置OpenCV 時靜態(tài)鏈接與動態(tài)鏈接的選擇。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
2017-01-01 
