程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> STL學習系列之二:標准模板庫(STL)介紹

STL學習系列之二:標准模板庫(STL)介紹

編輯:關於C++

此文為轉貼文章,由於原文運行在Linux下,我在vc6/7下進行調試,作了部分修改!注意:所有的代碼在vc6/vc7下調試通過!標准模板庫(STL)介紹

標准模板庫(STL)介紹

0 前言.

1 定義一個list

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

3 list的成員函數empty()

4 用for循環來處理list中的元素

5 用STL的通用算法for_each來處理list中的元素

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

7 使用count_if()的一個更加復雜的函數對象。

8 使用STL通用算法find()在list中查找對象

9 使用STL通用算法find_if()在list中搜索對象

10 使用STL通用算法search在list中找一個序列

11 使用list的成員函數sort()排序一個list。

12 用list的成員函數插入元素到list中

13 List 構造函數

14 使用list成員函數從list中刪除元素

15 用list成員函數remove()從list中刪除元素。

16 使用STL通用算法remove()從list中刪除元素

17 使用STL通用算法stable_partition()和list成員函數splice()來劃分一個list

18 結論

在field中使用STL

19 參考書目:

0 前言.

這篇文章是關於C++語言的一個新的擴展——標准模板庫的(Standard Template Library),也叫STL。

當我第一次打算寫一篇關於STL的文章的時候,我不得不承認我當時低估了這個話題的深度和廣度。有很多內容要含蓋,也有很多詳細描述STL的書。因此我重新考慮了一下我原來的想法。我為什麼要寫這篇文章,又為什麼要投稿呢?這會有什麽用呢?有再來一篇關於STL的文章的必要嗎?

當我翻開Musser and Saini的頁時,我看到了編程時代在我面前消融。我能看到深夜消失了, 目標軟件工程出現了。我看到了可維護的代碼。一年過去了,我使用STL寫的軟件仍然很容易維護。讓人吃驚的是其他人可以沒有我而維護的很好!

然而,我也記得在一開始的時候很難弄懂那些技術術語。一次,我買了Musser&Saini,每件事都依次出現,但是在那以前我最渴望得到的東西是一些好的例子。

當我開始的時候,作為C++一部分的Stroustrup還沒出來,它覆蓋了STL。

因此我想寫一篇關於一個STL程序員的真實生活的文章可能會有用。如果我手上有一些好的例子的話,特別是象這樣的新題目,我會學的更快。

另外一件事是STL應該很好用。因此,理論上說,我們應該可以馬上開始使用STL。

什麽是STL呢?STL就是Standard Template Library,標准模板庫。這可能是一個歷史上最令人興奮的工具的最無聊的術語。從根本上說,STL是一些“容器”的集合,這些“容器”有list, vector,set,map等,STL也是算法和其他一些組件的集合。這裡的“容器”和算法的集合指的是世界上很多聰明人很多年的傑作。

STL的目的是標准化組件,這樣你就不用重新開發它們了。你可以僅僅使用這些現成的組件。STL現在是C++的一部分,因此不用額外安裝什麽。它被內建在你的編譯器之內。因為STL的list是一個簡單的容器,所以我打算從它開始介紹STL如何使用。如果你懂得了這個概念,其他的就都沒有問題了。另外, list容器是相當簡單的,我們會看到這一點。

這篇文章中我們將會看到如何定義和初始化一個list,計算它的元素的數量,從一個list裡查找元素,刪除元素,和一些其他的操作。要作到這些,我們將會討論兩個不同的算法,STL通用算法都是可以操作不止一個容器的,而list的成員函數是list容器專有的操作。

這是三類主要的STL組件的簡明綱要。STL容器可以保存對象,內建對象和類對象。它們會安全的保存對象,並定義我們能夠操作的這個對象的接口。放在蛋架上的雞蛋不會滾到桌上。它們很安全。因此,在STL容器中的對象也很安全。我知道這個比喻聽起來很老土,但是它很正確。

STL算法是標准算法,我們可以把它們應用在那些容器中的對象上。這些算法都有很著名的執行特性。它們可以給對象排序,刪除它們,給它們記數,比較,找出特殊的對象,把它們合並到另一個容器中,以及執行其他有用的操作。

STL iterator就象是容器中指向對象的指針。STL的算法使用iterator在容器上進行操作。Iterator設置算法的邊界 ,容器的長度,和其他一些事情。舉個例子,有些iterator僅讓算法讀元素,有一些讓算法寫元素,有一些則兩者都行。Iterator也決定在容器中處理的方向。

你可以通過調用容器的成員函數begin()來得到一個指向一個容器起始位置的iterator。你可以調用一個容器的 end() 函數來得到過去的最後一個值(就是處理停在那的那個值)。

這就是STL所有的東西,容器、算法、和允許算法工作在容器中的元素上的iterator。算法以合適、標准的方法操作對象,並可通過iterator得到容器精確的長度。一旦做了這些,它們就在也不會“跑出邊界”。還有一些其他的對這些核心組件類型有功能性增強的組件,例如函數對象。我們將會看到有關這些的例子,現在 ,我們先來看一看STL的list。

1 定義一個list

我們可以象這樣來定義一個STL的list:

#include <string>
#include <list>
using namespace std;
int main (void)
{
 list<string> Milkshakes;
 return 0;
}

這就行了,你已經定義了一個list。簡單嗎?list<string> Milkshakes這句是你聲明了list<string>模板類 的一個實例,然後就是實例化這個類的一個對象。但是我們別急著做這個。在這一步其實你只需要知道你定義了 一個字符串的list。你需要包含提供STL list類的頭文件。我用gcc 2.7.2在我的Linux上編譯這個測試程序,例如:

g++ test1.cpp -o test1

注意iostream.h這個頭文件已經被STL的頭文件放棄了。這就是為什麼這個例子中沒有它的原因。

現在我們有了一個list,我們可以看實使用它來裝東西了。我們將把一個字符串加到這個list裡。有一個非常 重要的東西叫做list的值類型。值類型就是list中的對象的類型。在這個例子中,這個list的值類型就是字符串,string , 這是因為這個list用來放字符串。

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

#include <string>
#include <list>
using namespace std;
int main (void)
{
 list<string> Milkshakes;
 Milkshakes.push_back("Chocolate");
 Milkshakes.push_back("Strawberry");
 Milkshakes.push_front("Lime");
 Milkshakes.push_front("Vanilla");
 return 0;
}

我們現在有個4個字符串在list中。list的成員函數push_back()把一個對象放到一個list的後面,而 push_front()把對象放到前面。我通常把一些錯誤信息push_back()到一個list中去,然後push_front()一個標題到list中, 這樣它就會在這個錯誤消息以前打印它了。

3 list的成員函數empty()

知道一個list是否為空很重要。如果list為空,empty()這個成員函數返回真。我通常會這樣使用它。通篇程序我都用push_back()來把錯誤消息放到list中去。然後,通過調用empty() 我就可以說出這個程序是否報告了錯誤。如果我定義了一個list來放信息,一個放警告,一個放嚴重錯誤, 我就可以通過使用empty()輕易的說出到底有那種類型的錯誤發生了。

我可以整理這些list,然後在打印它們之前,用標題來整理它們,或者把它們排序成類。

這是我的意思:

/*
|| Using a list to track and report program messages and status
*/
//不要使用#include <iostream.h>
#include <iostream>
#include <string>
#include <list>
using namespace std;
int main (void)
{
 #define OK 0
 #define INFO 1
 #define WARNING 2
 int return_code;
 list<string> InfoMessages;
 list<string> WarningMessages;
 // during a program these messages are loaded at various points
 InfoMessages.push_back("Info: Program started");
 // do work...
 WarningMessages.push_back("Warning: No Customer records have been found");
 // do work...
 return_code = OK;
 if (!InfoMessages.empty()) {     // there were info messages
   InfoMessages.push_front("Informational Messages:");
   // ... print the info messages list, we'll see how later
   return_code = INFO;
 }
 if (!WarningMessages.empty()) {    // there were warning messages
   WarningMessages.push_front("Warning Messages:");
   // ... print the warning messages list, we'll see how later
   return_code = WARNING;
 }
 // If there were no messages say so.
 if (InfoMessages.empty() && WarningMessages.empty()) {
   cout << "There were no messages " << endl;
 }
 return return_code;
}

4 用for循環來處理list中的元素

我們想要遍歷一個list,比如打印一個中的所有對象來看看list上不同操作的結果。要一個元素一個元素的遍歷一個list, 我們可以這樣做:

/*
|| How to print the contents of a simple STL list. Whew!
*/
//不要使用#include <iostream.h>
#include <iostream>
#include <string>
#include <list>
using namespace std;
void main (void)
{
 list<string> Milkshakes;
 list<string>::iterator MilkshakeIterator;
 Milkshakes.push_back("Chocolate");
 Milkshakes.push_back("Strawberry");
 Milkshakes.push_front("Lime");
 Milkshakes.push_front("Vanilla");

 // print the milkshakes
 Milkshakes.push_front("The Milkshake Menu");
 Milkshakes.push_back("*** Thats the end ***");
 for (MilkshakeIterator=Milkshakes.begin();
     MilkshakeIterator!=Milkshakes.end();
     ++MilkshakeIterator)
 {
  // dereference the iterator to get the element
  cout << *MilkshakeIterator << endl;
 }  
}

這個程序定義了一個iterator,MilkshakeIterator。我們把它指向了這個list的第一個元素。這可以調用Milkshakes.begin()來作到,它會返回一個指向list開頭的iterator。然後我們把它和Milkshakes.end()的 返回值來做比較,當我們到了那兒的時候就停下來。

容器的end()函數會返回一個指向容器的最後一個位置的iterator。當我們到了那裡,就停止操作。我們不能不理容器的end()函數的返回值。我們僅知道它意味著已經處理到了這個容器的末尾,應該停止處理了。所有的STL容器都要這樣做。

在上面的例子中,每一次執行for循環,我們就重復引用iterator來得到我們打印的字符串。

在STL編程中,我們在每個算法中都使用一個或多個iterator。我們使用它們來存取容器中的對象。要存取一個給定的對象,我們把一個iterator指向它,然後間接引用這個iterator。

這個list容器,就象你所想的,它不支持在iterator加一個數來指向隔一個的對象。就是說,我們不能用Milkshakes.begin()+2來指向list中的第三個對象,因為STL的list是以雙鏈的list來實現的, 它不支持隨機存取。vector和deque(向量和雙端隊列)和一些其他的STL的容器可以支持隨機存取。

上面的程序打印出了list中的內容。任何人讀了它都能馬上明白它是怎麽工作的。它使用標准的iterator和標准 的list容器。沒有多少程序員依賴它裡面裝的東西, 僅僅是標准的C++。這是一個向前的重要步驟。這個例子使用STL使我們的軟件更加標准。

5 用STL的通用算法for_each來處理list中的元素

使用STL list和 iterator,我們要初始化、比較和給iterator增量來遍歷這個容器。STL通用的for_each 算法能夠減輕我們的工作。

/*
|| How to print a simple STL list MkII
*/
//不要使用#include <iostream.h>
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
PrintIt (string& StringToPrint) {
 cout << StringToPrint << endl;
}
void main (void) {
 list<string> FruitAndVegetables;
 FruitAndVegetables.push_back("carrot");
 FruitAndVegetables.push_back("pumpkin");
 FruitAndVegetables.push_back("potato");
 FruitAndVegetables.push_front("apple");
 FruitAndVegetables.push_front("pineapple");
 for_each (FruitAndVegetables.begin(), FruitAndVegetables.end(), PrintIt);
}

在這個程序中我們使用STL的通用算法for_each()來遍歷一個iterator的范圍,然後調用PrintIt()來處理每個對象。我們不需要初始化、比較和給iterator增量。for_each()為我們漂亮的完成了這些工作。我們執行於對象上的 操作被很好的打包在這個函數以外了,我們不用再做那樣的循環了,我們的代碼更加清晰了。

for_each算法引用了iterator范圍的概念,這是一個由起始iterator和一個末尾iterator指出的范圍。起始iterator指出操作由哪裡開始,末尾iterator指明到哪結束,但是它不包括在這個范圍內。用STL的通用算法count()來統計list中的元素個數。

STL的通用算法count()和count_it()用來給容器中的對象記數。就象for_each()一樣,count()和count_if() 算法也是在iterator范圍內來做的。

讓我們在一個學生測驗成績的list中來數一數滿分的個數。這是一個整型的List。

/*
|| How to count objects in an STL list
*/
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
void main (void)
{
 list<int> Scores;
 Scores.push_back(100); Scores.push_back(80);
 Scores.push_back(45); Scores.push_back(75);
 Scores.push_back(99); Scores.push_back(100);
 int NumberOf100Scores(0);
 //此行有錯count (Scores.begin(), Scores.end(), 100, NumberOf100Scores);
 NumberOf100Scores=count (Scores.begin(), Scores.end(), 100)
 cout << "There were " << NumberOf100Scores << " scores of 100" << endl;
}

count()算法統計等於某個值的對象的個數。上面的例子它檢查list中的每個整型對象是不是100。每次容器中的對象等於100,它就給NumberOf100Scores加1。這是程序的輸出:

There were 2 scores of 100

zbf批注:count的算法如下

template<class _II, class _Ty> inline

_CNTSIZ(_II) count(_II _F, _II _L, const _Ty& _V)

{_CNTSIZ(_II) _N = 0;

for (; _F != _L; ++_F)

if (*_F == _V)

++_N;

return (_N); }

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

count_if()是count()的一個更有趣的版本。他采用了STL的一個新組件,函數對象。count_if() 帶一個函數對象的參數。函數對象是一個至少帶有一個operator()方法的類。有些STL算法作為參數接收 函數對象並調用這個函數對象的operator()方法。

函數對象被約定為STL算法調用operator時返回true或false。它們根據這個來判定這個函數。舉個例子會 說的更清楚些。count_if()通過傳遞一個函數對象來作出比count()更加復雜的評估以確定一個對象是否應該被 記數。在這個例子裡我們將數一數牙刷的銷售數量。我們將提交包含四個字符的銷售碼和產品說明的銷售記錄。

/*
|| Using a function object to help count things
*/
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
const string ToothbrushCode("0003");
class IsAToothbrush
{
public: 
  bool operator() ( string& SalesRecord )
  {
   return SalesRecord.substr(0,4)==ToothbrushCode;
  }  
};
void main (void)
{
 list<string> SalesRecords;
 SalesRecords.push_back("0001 Soap");
 SalesRecords.push_back("0002 Shampoo");
 SalesRecords.push_back("0003 Toothbrush");
 SalesRecords.push_back("0004 Toothpaste");
 SalesRecords.push_back("0003 Toothbrush");

 int NumberOfToothbrushes(0);
 NumberOfToothbrushes=count_if (SalesRecords.begin(), SalesRecords.end(),
       IsAToothbrush());
 cout << "There were "
    << NumberOfToothbrushes
    << " toothbrushes sold" << endl;
}

這是這個程序的輸出:

There were 2 toothbrushes sold

這個程序是這樣工作的:定義一個函數對象類IsAToothbrush,這個類的對象能判斷出賣出的是否是牙刷 。如果這個記錄是賣出牙刷的記錄的話,函數調用operator()返回一個true,否則返回false。

count_if()算法由第一和第二兩個iterator參數指出的范圍來處理容器對象。它將對每個 IsAToothbrush?()返回true的容器中的對象增加NumberOfToothbrushes的值。

最後的結果是NumberOfToothbrushes這個變量保存了產品代碼域為"0003"的記錄的個數,也就是牙刷的個數。

注意count_if()的第三個參數IsAToothbrush(),它是由它的構造函數臨時構造的一個對象。你可以把IsAToothbrush類的一個臨時對象 傳遞給count_if()函數。count_if()將對該容器的每個對象調用這個函數。

7 使用count_if()的一個更加復雜的函數對象。

我們可以更進一步的研究一下函數對象。假設我們需要傳遞更多的信息給一個函數對象。我們不能通過 調用operator來作到這點,因為必須定義為一個list的中的對象的類型。然而我們通過為IsAToothbrush指出一個非缺省的構造函數就可以用任何我們所需要的信息來初始化它了。例如,我們可能需要每個牙刷有一個不定的代碼。我們可以把這個信息加到下面的函數對象中:

/*
|| Using a more complex function object
*/
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
class IsAToothbrush
{
public:
 IsAToothbrush(string& InToothbrushCode) :
   ToothbrushCode(InToothbrushCode) {}
 bool operator() (string& SalesRecord)
 {
  return SalesRecord.substr(0,4)==ToothbrushCode;
 }   
private:
 string ToothbrushCode;
};
void main (void)
{
 list<string> SalesRecords;
 SalesRecords.push_back("0001 Soap");
 SalesRecords.push_back("0002 Shampoo");
 SalesRecords.push_back("0003 Toothbrush");
 SalesRecords.push_back("0004 Toothpaste");
 SalesRecords.push_back("0003 Toothbrush");

 string VariableToothbrushCode("0003");
 int NumberOfToothbrushes(0);
 NumberOfToothbrushes=count_if (SalesRecords.begin(), SalesRecords.end(),
       IsAToothbrush(VariableToothbrushCode));
 cout << "There were "
    << NumberOfToothbrushes
    << " toothbrushes matching code "
    << VariableToothbrushCode
    << " sold"
    << endl;
}

程序的輸出是:

There were 2 toothbrushes matching code 0003 sold

這個例子演示了如何向函數對象傳遞信息。你可以定義任意你想要的構造函數,你可以在函數對象中做任何你 想做的處理,都可以合法編譯通過。

你可以看到函數對象真的擴展了基本記數算法。

到現在為止,我們都學習了:

定義一個list

向list中加入元素

如何知道list是否為空

如何使用for循環來遍歷一個list

如何使用STL的通用算法for_each來遍歷list

list成員函數begin() 和 end() 以及它們的意義

iterator范圍的概念和一個范圍的最後一個位置實際上並不被處理這一事實

如何使用STL通用算法count()和count_if()來對一個list中的對象記數

如何定義一個函數對象

我選用這些例子來演示list的一般操作。如果你懂了這些基本原理,你就可以毫無疑問的使用STL了 建議你作一些練習。我們現在用一些更加復雜的操作來擴展我們的知識,包括list成員函數和STL通用算法。

8 使用STL通用算法find()在list中查找對象

我們如何在list中查找東西呢?STL的通用算法find()和find_if()可以做這些。就象for_each(), count(), count_if() 一樣,這些算法也使用iterator范圍,這個范圍指出一個list或任意 其他容器中的一部分來處理。通常首iterator指著開始的位置,次iterator指著停止處理的地方。由次iterator指出的元素不被處理。這是find()如何工作:

/*
|| How to find things in an STL list
*/
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
void main (void) {
  list<string> Fruit;
  list<string>::iterator FruitIterator;
  Fruit.push_back("Apple");
  Fruit.push_back("Pineapple");
  Fruit.push_back("Star Apple");
  FruitIterator = find (Fruit.begin(), Fruit.end(), "Pineapple");
  if (FruitIterator == Fruit.end()) {
    cout << "Fruit not found in list" << endl;
  }
  else {
    cout << *FruitIterator << endl;
  }
}

輸出是:

Pineapple

如果沒有找到指出的對象,就會返回Fruit.end()的值,要是找到了就返回一個指著找到的對象的iterator

9 使用STL通用算法find_if()在list中搜索對象

這是find()的一個更強大的版本。這個例子演示了find_if(),它接收一個函數對象的參數作為參數, 並使用它來做更復雜的評價對象是否和給出的查找條件相付。假設我們的list中有一些按年代排列的包含了事件和日期的記錄。我們希望找出發生在1997年的事件。

/*
|| How to find things in an STL list MkII
*/
#include <string>
#include <list>
#include <algorithm>
class EventIsIn1997 {
public:
  bool operator () (string& EventRecord) {
    // year field is at position 12 for 4 characters in EventRecord
    return EventRecord.substr(12,4)=="1997";
  }
};
void main (void) {
  list<string> Events;
  // string positions 0123456789012345678901234567890123456789012345
  Events.push_back("07 January 1995 Draft plan of house prepared");
  Events.push_back("07 February 1996 Detailed plan of house prepared");
  Events.push_back("10 January 1997 Client agrees to job");
  Events.push_back("15 January 1997 Builder starts work on bedroom");
  Events.push_back("30 April  1997 Builder finishes work");
  list<string>::iterator EventIterator = find_if (Events.begin(), Events.end(), EventIsIn1997());
  // find_if completes the first time EventIsIn1997()() returns true
  // for any object. It returns an iterator to that object which we
  // can dereference to get the object, or if EventIsIn1997()() never
  // returned true, find_if returns end()
  if (EventIterator==Events.end()) {
    cout << "Event not found in list" << endl;
  }
  else {
    cout << *EventIterator << endl;
  }
}

這是程序的輸出:

10 January 1997 Client agrees to job

10 使用STL通用算法search在list中找一個序列

一些字符在STL容器中很好處理,讓我們看一看一個難處理的字符序列。我們將定義一個list來放字符。

list<char> Characters;

現在我們有了一個字符序列,它不用任何幫助就知道然後管理內存。它知道它是從哪裡開始、到哪裡結束。它非常有用。我不知道我是否說過以null結尾的字符數組。

讓我們加入一些我們喜歡的字符到這個list中:

Characters.push_back('\0');
Characters.push_back('\0');
Characters.push_back('1');
Characters.push_back('2');

我們將得到多少個空字符呢?

int NumberOfNullCharacters(0);
count(Characters.begin(), Characters.end(), '\0', NumberOfNullCharacters);
cout << "We have " << NumberOfNullCharacters << endl;

讓我們找字符'1'

list<char>::iterator Iter;
Iter = find(Characters.begin(), Characters.end(), '1');
cout << "We found " << *Iter << endl;

這個例子演示了STL容器允許你以更標准的方法來處理空字符。現在讓我們用STL的search算法來搜索容器中 的兩個null。就象你猜的一樣,STL通用算法search()用來搜索一個容器,但是是搜索一個元素串,不象find()和find_if() 只搜索單個的元素。

/*
|| How to use the search algorithm in an STL list
*/
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
void main ( void){
  list<char> TargetCharacters;
  list<char> ListOfCharacters;
  TargetCharacters.push_back('\0');
  TargetCharacters.push_back('\0');
  ListOfCharacters.push_back('1');
  ListOfCharacters.push_back('2');
  ListOfCharacters.push_back('\0');
  ListOfCharacters.push_back('\0');
  list<char>::iterator PositionOfNulls = search(ListOfCharacters.begin(), ListOfCharacters.end(), TargetCharacters.begin(), TargetCharacters.end());
  if (PositionOfNulls!=ListOfCharacters.end())
    cout << "We found the nulls" << endl;
}

The output of the program will be 這是程序的輸出:

We found the nulls

search算法在一個序列中找另一個序列的第一次出現的位置。在這個例子裡我們在ListOfCharacters中 找TargetCharacters這個序列的第一次出現,TargetCharacters是包含兩個null字符的序列。search的參數是兩個指著查找目標的iterator和兩個指著搜索范圍的iterators。因此我們我們在整個的ListOfCharacters的范圍內查找TargetCharacters這個list的整個序列。---www.bianceng.cn

如果TargetCharacters被發現,search就會返回一個指著ListOfCharacters中序列匹配的第一個 字符的iterator。如果沒有找到匹配項,search返回ListOfCharacters.end()的值。

11 使用list的成員函數sort()排序一個list。

要排序一個list,我們要用list的成員函數sort(),而不是通用算法sort()。所有我們用過的算法都是 通用算法。然而,在STL中有時容器支持它自己對一個特殊算法的實現,這通常是為了提高性能。

在這個例子中,list容器有它自己的sort算法,這是因為通用算法僅能為那些提供隨機存取裡面元素 的容器排序,而由於list是作為一個連接的鏈表實現的,它不支持對它裡面的元素隨機存取。所以就需要一個特殊的 sort()成員函數來排序list。

由於各種原因,容器在性能需要較高或有特殊效果需求的場合支持外部函數(extra functions), 這通過利用構造函數的結構特性可以作到。

/*
|| How to sort an STL list
*/
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
PrintIt (string& StringToPrint) { cout << StringToPrint << endl;}
void main (void) {
  list<string> Staff;
  list<string>::iterator PeopleIterator;
  Staff.push_back("John");
  Staff.push_back("Bill");
  Staff.push_back("Tony");
  Staff.push_back("Fidel");
  Staff.push_back("Nelson");
  cout << "The unsorted list " << endl;
  for_each(Staff.begin(), Staff.end(), PrintIt) ;
  Staff.sort();
  cout << "The sorted list " << endl;
  for_each(Staff.begin(), Staff.end(), PrintIt);
}
輸出是:
The unsorted list
John
Bill
Tony
Fidel
Nelson
The sorted list
Bill
Fidel
John
Nelson
Tony
12 用list的成員函數插入元素到list中

list的成員函數push_front()和push_back()分別把元素加入到list的前面和後面。你可以使用insert() 把對象插入到list中的任何地方。

insert()可以加入一個對象,一個對象的若干份拷貝,或者一個范圍以內的對象。這裡是一些 插入對象到list中的例子:

/*
|| Using insert to insert elements into a list.
*/
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
void main (void) {
  list<int> list1;
  list<int> ::iterator List1Itetator;
  /*
  || Put integers 0 to 9 in the list
  */
  for (int i = 0; i < 10; ++i) list1.push_back(i);
  /*
  || Insert -1 using the insert member function
  || Our list will contain -1,0,1,2,3,4,5,6,7,8,9
  */
    list1.insert(list1.begin(), -1);
  /*
  || Insert an element at the end using insert
  || Our list will contain -1,0,1,2,3,4,5,6,7,8,9,10
  */
    list1.insert(list1.end(), 10);
  /*
  || Inserting a range from another container
  || Our list will contain -1,0,1,2,3,4,5,6,7,8,9,10,11,12
  */
  int IntArray[2] = {11,12};
  list1.insert(list1.end(), &IntArray[0], &IntArray[2]);
  /*
  || As an exercise put the code in here to print the lists!
  || Hint: use PrintIt and accept an interger
  */
  //output
  for(List1Itetator=list1.begin();List1Itetator!=list1.end();
   List1Itetator++)
  {
   cout<<*List1Itetator<<endl;
  }
}

注意,insert()函數把一個或若干個元素插入到你指出的iterator的位置。你的元素將出現在 iterator指出的位置以前。

13 List 構造函數

我們已經象這樣定義了list:

list<int> Fred;

你也可以象這樣定義一個list,並同時初始化它的元素:

// define a list of 10 elements and initialise them all to 0
list<int> Fred(10, 0);
// list now contains 0,0,0,0,0,0,0,0,0,0

或者你可以定義一個list並用另一個STL容器的一個范圍來初始化它,這個STL容器不一定是一個list, 僅僅需要是元素類型相同的的容器就可以。

vector<int> Harry;
Harry.push_back(1);
Harry.push_back(2);
#
// define a list and initialise it with the elements in Harry
list<int> Bill(Harry.begin(), Harry.end());
// Bill now contains 1,2
14 使用list成員函數從list中刪除元素

list成員函數pop_front()刪掉list中的第一個元素,pop_back()刪掉最後一個元素。函數erase()刪掉由一個iterator指出的元素。還有另一個erase()函數可以刪掉一個范圍的元素。

/*
|| Erasing objects from a list
*/
#include <list>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
void   main (void) {
  list<int> list1; // define a list of integers
  /*
  || Put some numbers in the list
  || It now contains 0,1,2,3,4,5,6,7,8,9
  */
  for (int i = 0; i < 10; ++i) list1.push_back(i);
  list1.pop_front(); // erase the first element 0
  list1.pop_back(); // erase the last element 9
  list1.erase(list1.begin()); // erase the first element (1) using an iterator
  list1.erase(list1.begin(), list1.end()); // erase all the remaining elements
  cout << "list contains " << list1.size() << " elements" << endl;
}

輸出是:

list contains 0 elements

15 用list成員函數remove()從list中刪除元素。

list的成員函數remove()用來從list中刪除元素。

/*
|| Using the list member function remove to remove elements
*/
#include <string>
#include <list>
#include <algorithm>
#include<iostream>
using namespace std;
PrintIt (const string& StringToPrint) {
  cout << StringToPrint << endl;
}
void main (void) {
  list<string> Birds;
  Birds.push_back("cockatoo");
  Birds.push_back("galah");
  Birds.push_back("cockatoo");
  Birds.push_back("rosella");
  Birds.push_back("corella");
  cout << "Original list with cockatoos" << endl;
  for_each(Birds.begin(), Birds.end(), PrintIt);
  Birds.remove("cockatoo");
  cout << "Now no cockatoos" << endl;
  for_each(Birds.begin(), Birds.end(), PrintIt);
}
輸出是:
Original list with cockatoos
cockatoo
galah
cockatoo
rosella
corella
Now no cockatoos
galah
rosella
corella

16 使用STL通用算法remove()從list中刪除元素

通用算法remove()使用和list的成員函數不同的方式工作。一般情況下不改變容器的大小。

/*
|| Using the generic remove algorithm to remove list elements
*/
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
PrintIt(string& AString) { cout << AString << endl; }
void main (void) {
  list<string> Birds;
  list<string>::iterator NewEnd;
  Birds.push_back("cockatoo");
  Birds.push_back("galah");
  Birds.push_back("cockatoo");
  Birds.push_back("rosella");
  Birds.push_back("king parrot");
  cout << "Original list" << endl;
  for_each(Birds.begin(), Birds.end(), PrintIt);
  NewEnd = remove(Birds.begin(), Birds.end(), "cockatoo");
  cout << endl << "List according to new past the end iterator" << endl;
  for_each(Birds.begin(), NewEnd, PrintIt);
  cout << endl << "Original list now. Care required!" << endl;
  for_each(Birds.begin(), Birds.end(), PrintIt);//zbf.不能用此種方法打印
}
輸出結果將為:
Original list
cockatoo
galah
cockatoo
rosella
king parrot
List according to new past the end iterator
galah
rosella
king parrot
Original list now. Care required!
galah
rosella
king parrot
rosella
king parrot

通用remove()算法返回一個指向新的list的結尾的iterator。從開始到這個新的結尾(不含新結尾元素)的范圍 包含了remove後剩下所有元素。你可以用list成員函數erase函數來刪除從新結尾到老結尾的部分。

17 使用STL通用算法stable_partition()和list成員函數splice()來劃分一個list

我們將完成一個稍微有點復雜的例子。它演示STL通用算法stable_partition()算法和一個list成員函數 splice()的變化。注意函數對象的使用和沒有使用循環。通過簡單的語句調用STL算法來控制。

stable_partition()是一個有趣的函數。它重新排列元素,使得滿足指定條件的元素排在 不滿足條件的元素前面。它維持著兩組元素的順序關系。

splice 把另一個list中的元素結合到一個list中。它從源list中刪除元素。

在這個例子中,我們想從命令行接收一些標志和四個文件名。文件名必須’按順序出現。通過使用stable_partition() 我們可以接收和文件名混為任何位置的標志,並且不打亂文件名的順序就把它們放到一起。

由於記數和查找算法都很易用,我們調用這些算法來決定哪個標志被設置而哪個標志未被設置。我發現容器用來管理少量的象這樣的動態數據。

/*
|| Using the STL stable_partition algorithm
|| Takes any number of flags on the command line and
|| four filenames in order.
*/
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
using namespace std;
PrintIt ( string& AString { cout << AString << endl; }
class IsAFlag {
public:
  bool operator () (string& PossibleFlag) {
    return PossibleFlag.substr(0,1)=="-";
  }
};
class IsAFileName {
public:
  bool operator () (string& StringToCheck) {
    return !IsAFlag()(StringToCheck);
  }
};
class IsHelpFlag {
public:
  bool operator () (string& PossibleHelpFlag) {
    return PossibleHelpFlag=="-h";
  }
};
void main (int argc, char *argv[]) {
  list<string> CmdLineParameters; // the command line parameters
  list<string>::iterator StartOfFiles; // start of filenames
  list<string> Flags; // list of flags
  list<string> FileNames; // list of filenames
  for (int i = 0; i < argc; ++i) CmdLineParameters.push_back(argv[i]);
    CmdLineParameters.pop_front(); // we don't want the program name
  // make sure we have the four mandatory file names
  int NumberOfFiles(0);
  count_if(CmdLineParameters.begin(), CmdLineParameters.end(), IsAFileName(), NumberOfFiles);
  cout << "The " << (NumberOfFiles == 4 ? "correct " : "wrong ") << "number (" << NumberOfFiles << ") of file names were specified" << endl;
// move any flags to the beginning
  StartOfFiles = stable_partition(CmdLineParameters.begin(), CmdLineParameters.end(), IsAFlag());
  cout << "Command line parameters after stable partition" << endl;
  for_each(CmdLineParameters.begin(), CmdLineParameters.end(), PrintIt);
  // Splice any flags from the original CmdLineParameters list into Flags list.
  Flags.splice(Flags.begin(), CmdLineParameters, CmdLineParameters.begin(), StartOfFiles);
  if (!Flags.empty()) {
    cout << "Flags specified were:" << endl;
    for_each(Flags.begin(), Flags.end(), PrintIt);
  }
  else {
    cout << "No flags were specified" << endl;
  }
  // parameters list now contains only filenames. Splice them into FileNames list.
  FileNames.splice(FileNames.begin(), CmdLineParameters, CmdLineParameters.begin(), CmdLineParameters.end());
  if (!FileNames.empty()) {
    cout << "Files specified (in order) were:" << endl;
    for_each(FileNames.begin(), FileNames.end(), PrintIt);
  }
  else {
    cout << "No files were specified" << endl;
  }
  // check if the help flag was specified
  if (find_if(Flags.begin(), Flags.end(), IsHelpFlag())!=Flags.end()) {
    cout << "The help flag was specified" << endl;
  }
  // open the files and do whatever you do
}

給出這樣的命令行:

//zbf:在vc6IDE下可以模擬出一樣的結果

test17 -w linux -o is -w great

輸出是:

The wrong number (3) of file names were specified
Command line parameters after stable partition
-w
-o
-w
linux
is
great
Flags specified were:
-w
-o
-w
Files specified (in order) were:
linux
is
great

18 結論

我們僅僅簡單的談了談你可以用list做的事情。我們沒有說明一個對象的用戶定義類,雖然這個不難。

如果你懂了剛才說的這些算法背後的概念,那麼你使用剩下的那些算法就應該沒有問題了。使用STL 最重要的東西就是得到基本理論。

STL的關鍵實際上是iterator。STL算法作為參數使用iterator,他們指出一個范圍,有時是一個范圍, 有時是兩個。STL容器支持iterator,這就是為什麼我們說 list<int>::iterator, 或 list<char>::iterator, 或 list<string>::iterator.

iterator有很好的定義繼承性。它們非常有用。某些iterator僅支持對一個容器只讀,某些 僅支持寫,還有一些僅能向前指,有一些是雙向的。有一些iterator支持對一個容器的隨機存取。

STL算法需要某個iterator作為“動力” 如果一個容器不提供iterator作為“動力”,那麼這個算法將無法編譯。例如,list容器僅提供雙向的 iterator。通常的sort()算法需要隨機存取的iterator。這就是為什麼我們需要一個特別的list成員函數sort()。

要合適的實際使用STL,你需要仔細學習各種不同的iterator。你需要知道每種容器都支持那類iterator。你還需要知道算法需要那種iterator,你當然也需要懂得你可以有那種iterator。

在field中使用STL

去年,我曾用STL寫過幾個商業程序。它在很多方面減少了我的工作量,也排除了很多邏輯錯誤。

最大的一個程序有大約5000行。可能最驚人的事情就是它的速度。它讀入並處理一個1-2兆的 報告文件僅花大約20秒。我是在linux上用gcc2.7.2開發的,現在運行在HP-UX機器上。它一共用了大約50和函數對象和很多容器,這些容器的大小從小list到一個有14,000個元素的map都有。

一個程序中的函數對象是處於一個繼承樹中,頂層的函數對象調用低層的函數對象。我大量的使用STL算法for_each() ,find(),find_if(),count()和count_if(),我盡量減少使用程序內部的函數,而使用STL的算法調用。

STL傾向於自動的把代碼組織成清晰的控制和支持模塊。通過小心使用函數對象並給它們 起有意義的名字,我使它們在我的軟件的控制流中流動。

還有很多關於STL編程要知道的東西,我希望你通過這些例子可以愉快的工作。

參考數目中的兩本書在web上都有勘誤表,你可以自己改正它們。

Stroustrup在每一章後面都有個建議欄,特別是對於出學者有用。正本書比早期的版本更加健談。它也更大了。書店裡還可以找到其他幾本關於STL的教科書。去看看,也許你能發現什麼。

19 參考書目:

The STL Tutorial and Reference Guide, David Musser and Atul Saini. Addison Wesley 1996. 《STL教程和參考手冊》

The C++ Programming Language 3e, Bjarne Stroustrup. Addison Wesley 1997

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved