一步一步學STL標準模板庫

來源:互聯網
上載者:User

list 的使用

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

1)、如何定義一個list對象

#include <list>
int main (void)
{
  list<char > cList; //聲明了list<char>模板類 的一個執行個體
}

2)、使用list的成員函數push_back和push_front插入一個元素到list中

cList. push_back(‘a’); //把一個對象放到一個list的後面
cList. push_front (‘b’); //把一個對象放到一個list的前面

3)、使 用list的成員函數empty()判斷list是否為空白

if (cList.empty())
{
  printf(“this list is empty”);
}

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

list< char>::iterator charIterator;
for(cIterator = cList.Begin();cIterator != cList.end();cIterator++)
{
  printf(“%c”, *cIterator);
} //輸出list中的所有對象

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

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

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

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

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

const char c (‘c’);
class IsC
{
public:
  bool operator() ( char& ch )
  {
    return ch== c;
  }
};
int numC;
numC = count_if (cList.begin(), cList.end(),IsC());//統計c的數量;

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

7)、使用STL通用演算法find()在list中尋找對象

list<char >::iterator FindIterator;
FindIterator = find(cList.begin(), cList.end(), ‘c’);
If (FindIterator == cList.end())
{
  printf(“not find the char ‘c’!”);
}
else
{
  printf(“%c”, * FindIterator);
}

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.