天天看點

STL學習筆記之STL介紹(中)

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

STL的通用算法find()和find_if()可以做這些。就象for_each(), count(), count_if() 一樣,這些算法也使用iterator範圍,這個範圍指出一個list或任意其他容器中的一部分來處理。通常首iterator指着開始的位置,次iterator指着停止處理的地方。由次iterator指出的元素不被處理。

/* 
|| How to find things in an STL list 
*/ 
#include <string> 
#include <list> 
#include <algorithm> 

int 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 

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

/* 
|| 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"; 
    } 
}; 
 
int 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

使用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> 
 
int 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 programwill be 這是程式的輸出:

We found the nulls 

search算法在一個序列中找另一個序列的第一次出現的位置。在這個例子裡我們在ListOfCharacters中找TargetCharacters這個序列的第一次出現,TargetCharacters是包含兩個null字元的序列。

search的參數是兩個指着查找目标的iterator和兩個指着搜尋範圍的iterators。是以我們我們在整個的ListOfCharacters的範圍内查找TargetCharacters這個list的整個序列。

如果TargetCharacters被發現,search就會傳回一個指着ListOfCharacters中序列比對的第一個字元的iterator。如果沒有找到比對項,search傳回ListOfCharacters.end()的值。

使用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> 
 
PrintIt (string& StringToPrint) { cout << StringToPrint << endl;} 
 
int 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); 
} 
           

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

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

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

/* 
|| Using insert to insert elements into a list. 
*/ 
#include <list> 
 
int main (void) { 
    list<int> list1; 
 
    /* 
    || 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 
    */ 
} 
           

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

繼續閱讀