雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

C++ list的實例詳解

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊:

 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ū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

上一篇:C語言菜鳥基礎教程之條件判斷

欄    目:C語言

下一篇:C語言菜鳥基礎教程之數(shù)據(jù)類型

本文標題:C++ list的實例詳解

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/1134.html

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有