1. 程式人生 > >C++List模板類的使用

C++List模板類的使用

List的使用

在使用list必須包括標頭檔案#include <list>

如何定義一個list物件

  1. #include <list>
  2. int main (void)  
  3. {  
  4.     list<char > cList; //聲明瞭list<char>模板類 的一個例項
  5. }  

使用list的成員函式push_back和push_front插入一個元素到list中

cList. push_back(‘a’); //把一個物件放到一個list的後面

cList. push_front (‘b’); //把一個物件放到一個list的前面

使用list的成員函式empty()判斷list是否為空

  1. if (cList.empty())  
  2. {  
  3.     printf(“this list is empty”);  
  4. }  


用list< char >::iterator得到指向list的指標

  1. list< char>::iterator charIterator;  
  2. for(cIterator = cList.Begin();cIterator != cList.end();cIterator++)  
  3. {  
  4.     printf(“%c”, *cIterator);  
  5. //輸出list中的所有物件

說明:cList.Begin()和cList.end()函式返回指向list< char >::iterator的指標,由於list採用連結串列結構,因此它不支援隨機存取,因此不能用cList.begin()+3來指向list中的第 四個物件,vector和deque支援隨機存取。

用STL的通用演算法count()來統計list中的元素個數

int cNum;

char ch = ’b’;

cNum = count(cList.Begin(), cList.end(), ch); //統計list中的字元b的個數

說明:在使用count()函式之前必須加入#include <algorithm>

用STL的通用演算法count_if ()來統計list中的元素個數

  1. constchar c(‘c’);  
  2. class IsC  
  3. {  
  4. public:  
  5.     bool operator() ( char& ch )  
  6.     {  
  7.         return
     ch== c;  
  8.     }  
  9. };  
  10. int numC;  
  11. numC = count_if (cList.begin(), cList.end(),IsC());//統計c的數量;

說明:count_if() 帶一個函式物件的引數,函式物件是一個至少帶有一個operator()方法的類函式物件被約定為STL演算法呼叫operator時返回true或 false。它們根據這個來判定這個函式。舉個例子會 說的更清楚些。count_if()通過傳遞一個函式物件來作出比count()更加複雜的評估以確定一個物件是否應該被記數。

使用STL通用演算法find()在list中查詢物件

  1. list<char >::iterator FindIterator;  
  2. FindIterator = find(cList.begin(), cList.end(), ‘c’);  
  3. If (FindIterator == cList.end())  
  4. {  
  5.     printf(“not find the char ‘c’!”);  
  6. }  
  7. else
  8. {  
  9.     printf(“%c”, * FindIterator);  
  10. }  

說明:如果沒有找到指定的物件,就會返回cList.end()的值,找到了就返回一個指向物件iterator的指標。

使用STL通用演算法find_if()在list中查詢物件

  1. constchar c(‘c’);  
  2. class c  
  3. {  
  4. public:  
  5.     bool operator() ( char& ch )  
  6.     {  
  7.         return ch== c;  
  8.     }  
  9. };  
  10. list<char>::iterator FindIterator  
  11. FindIterator = find_if (cList.begin(), cList.end(),IsC());//查詢字串c;

說明:如果沒有找到指定的物件,就會返回cList.end()的值,找到了就返回一個指向物件iterator的指標。

使用list的成員函式sort()排序

cList.sort();

使用list的成員函式insert插入一個物件到list中

  1. cList.insert(cLiset.end, ‘c’); ///在list末尾插入字元‘c’
  2. char ch[3] ={‘a’, ‘b’, ‘c’};  
  3. cList.insert(cList.end, &ch[0], & ch[3] ); //插入三個字元到list中
  4. 說明:insert()函式把一個或多個元素插入到指出的iterator位置。元素將出現在 iterator指出的位置以前。  
  5. 如何在list中刪除元素  
  6. cList.pop_front(); //刪除第一個元素
  7. cList.pop_back(); //刪除最後一個元素
  8. cList. Erase(cList.begin()); //使用iterator刪除第一個元素;
  9. cList. Erase(cList.begin(), cList.End()); //使用iterator刪除所有元素;
  10. cList.remove(‘c’); //使用remove函式刪除指定的物件;
  11. list<char>::iterator newEnd;  
  12. //刪除所有的’c’ ,並返回指向新的list的結尾的iterator
  13. newEnd = cList.remove(cList.begin(), cList.end(), ‘c’);