C++ list

來源:互聯網
上載者:User

 

Source:

#include <iostream><br />#include <list><br />#include <numeric><br />#include <algorithm><br />using namespace std; </p><p>typedef list<int> LISTINT; //建立一個list容器的執行個體LISTINT<br />typedef list<int> LISTCHAR; //建立一個list容器的執行個體LISTCHAR<br />int main(void) {<br />LISTINT listOne; //用LISTINT建立一個名為listOne的list對象<br />LISTINT::iterator i; //聲明i為迭代器<br />listOne.push_front (2); //從前面向listOne容器中添加資料<br />listOne.push_front (1);<br />listOne.push_back (3); //從後面向listOne容器中添加資料<br />listOne.push_back (4); </p><p>cout<<"listOne.begin()--- listOne.end():"<<endl; //從前向後顯示listOne中的資料<br />for (i = listOne.begin(); i != listOne.end(); ++i)<br />cout << *i << " ";<br />cout << endl; </p><p>LISTINT::reverse_iterator ir; //從後向後顯示listOne中的資料<br />cout<<"listOne.rbegin()---listOne.rend():"<<endl;<br />for (ir =listOne.rbegin(); ir!=listOne.rend();ir++)<br />cout << *ir << " ";<br />cout << endl; </p><p>int result = accumulate(listOne.begin(), listOne.end(),0); //使用STL的accumulate(累加)演算法<br />cout<<"Sum="<<result<<endl; </p><p>LISTCHAR listTwo; //用LISTCHAR建立一個名為listOne的list對象<br />LISTCHAR::iterator j; //聲明j為迭代器<br />listTwo.push_front ('A'); //從前面向listTwo容器中添加資料<br />listTwo.push_front ('B');<br />listTwo.push_back ('x'); //從後面向listTwo容器中添加資料<br />listTwo.push_back ('y');<br />cout<<"listTwo.begin()---listTwo.end():"<<endl; //從前向後顯示listTwo中的資料<br />for (j = listTwo.begin(); j != listTwo.end(); ++j)<br />cout << char(*j) << " ";<br />cout << endl;<br />//使用STL的max_element演算法求listTwo中的最大元素並顯示<br />j=max_element(listTwo.begin(),listTwo.end());<br />cout << "The maximum element in listTwo is: "<<char(*j)<<endl;<br />return 0;<br />}<br />

 

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

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.