三十分鐘掌握STL
這是本小人書(shū)。原名是《using stl》,不知道是誰(shuí)寫(xiě)的。不過(guò)我倒覺(jué)得很有趣,所 以化了兩個(gè)晚上把它翻譯出來(lái)。我沒(méi)有對(duì)翻譯出來(lái)的內(nèi)容校驗(yàn)過(guò)。如果你沒(méi)法在三十 分鐘內(nèi)覺(jué)得有所收獲,那么趕緊扔了它。文中我省略了很多東西。心疼那,浪費(fèi)我兩 個(gè)晚上。 譯者:kary
contact:karymay@163.net
STL概述 STL的一個(gè)重要特點(diǎn)是數(shù)據(jù)結(jié)構(gòu)和算法的分離。盡管這是個(gè)簡(jiǎn)單的概念,但這種分離 確實(shí)使得STL變得非常通用。例如,由于STL的sort()函數(shù)是完全通用的,你可以用它 來(lái)操作幾乎任何數(shù)據(jù)集合,包括鏈表,容器和數(shù)組。
要點(diǎn) STL算法作為模板函數(shù)提供。為了和其他組件相區(qū)別,在本書(shū)中STL算法以后接一對(duì)圓 括弧的方式表示,例如sort()。
STL另一個(gè)重要特性是它不是面向?qū)ο蟮摹榱司哂凶銐蛲ㄓ眯裕琒TL主要依賴(lài)于模板 而不是封裝,繼承和虛函數(shù)(多態(tài)性)——OOP的三個(gè)要素。你在STL中找不到任何明 顯的類(lèi)繼承關(guān)系。這好像是一種倒退,但這正好是使得STL的組件具有廣泛通用性的 底層特征。另外,由于STL是基于模板,內(nèi)聯(lián)函數(shù)的使用使得生成的代碼短小***效。
提示
確保在編譯使用了STL的程序中至少要使用-O優(yōu)化來(lái)保證內(nèi)聯(lián)擴(kuò)展。STL提供了大量的 模板類(lèi)和函數(shù),可以在OOP和常規(guī)編程中使用。所有的STL的大約50個(gè)算法都是完全通 用的,而且不依賴(lài)于任何特定的數(shù)據(jù)類(lèi)型。下面的小節(jié)說(shuō)明了三個(gè)基本的STL組件:
1) 迭代器提供了訪問(wèn)容器中對(duì)象的方法。例如,可以使用一對(duì)迭代器指 定list或vector中的一定范圍的對(duì)象。迭代器就如同一個(gè)指針。事實(shí)上,C++的指針 也是一種迭代器。但是,迭代器也可以是那些定義了operator*()以及其他類(lèi)似于指 針的操作符地方法的類(lèi)對(duì)象。
2) 容器是一種數(shù)據(jù)結(jié)構(gòu),如list,vector,和deques ,以模板類(lèi)的方 法提供。為了訪問(wèn)容器中的數(shù)據(jù),可以使用由容器類(lèi)輸出的迭代器。
3) 算法是用來(lái)操作容器中的數(shù)據(jù)的模板函數(shù)。例如,STL用sort()來(lái)對(duì) 一個(gè)vector中的數(shù)據(jù)進(jìn)行排序,用find()來(lái)搜索一個(gè)list中的對(duì)象。函數(shù)本身與他們 操作的數(shù)據(jù)的結(jié)構(gòu)和類(lèi)型無(wú)關(guān),因此他們可以在從簡(jiǎn)單數(shù)組到***度復(fù)雜容器的任何數(shù) 據(jù)結(jié)構(gòu)上使用。
頭文件 為了避免和其他頭文件沖突, STL的頭文件不再使用常規(guī)的.h擴(kuò)展。為了包含標(biāo)準(zhǔn)的 string類(lèi),迭代器和算法,用下面的指示符:
#i nclude <string>
#i nclude <iterator>
#i nclude <algorithm>
如果你查看STL的頭文件,你可以看到象iterator.h和stl_iterator.h這樣的頭文件 。由于這些名字在各種STL實(shí)現(xiàn)之間都可能不同,你應(yīng)該避免使用這些名字來(lái)引用這 些頭文件。為了確保可移植性,使用相應(yīng)的沒(méi)有.h后綴的文件名。表1列出了最常使 用的各種容器類(lèi)的頭文件。該表并不完整,對(duì)于其他頭文件,我將在本章和后面的兩 章中介紹。
表 1. STL頭文件和容器類(lèi)
#i nclude Container Class
<deque> deque
<list> list
<map> map, multimap
<queue> queue, priority_queue
<set> set, multiset
<stack> stack
<vector> vector, vector<bool>
名字空間 你的編譯器可能不能識(shí)別名字空間。名字空間就好像一個(gè)信封,將標(biāo)志符封裝在另一 個(gè)名字中。標(biāo)志符只在名字空間中存在,因而避免了和其他標(biāo)志符沖突。例如,可能 有其他庫(kù)和程序模塊定義了sort()函數(shù),為了避免和STL地sort()算法沖突,STL的sort ()以及其他標(biāo)志符都封裝在名字空間std中。STL的sort()算法編譯為std::sort(), 從而避免了名字沖突。
盡管你的編譯器可能沒(méi)有實(shí)現(xiàn)名字空間,你仍然可以使用他們。為了使用STL,可以 將下面的指示符插入到你的源代碼文件中,典型地是在所有的#i nclude指示符的后面 :
using namespace std;
迭代器 迭代器提供對(duì)一個(gè)容器中的對(duì)象的訪問(wèn)方法,并且定義了容器中對(duì)象的范圍。迭代器 就如同一個(gè)指針。事實(shí)上,C++的指針也是一種迭代器。但是,迭代器不僅僅是指針 ,因此你不能認(rèn)為他們一定具有地址值。例如,一個(gè)數(shù)組索引,也可以認(rèn)為是一種迭 代器。
迭代器有各種不同的創(chuàng)建方法。程序可能把迭代器作為一個(gè)變量創(chuàng)建。一個(gè)STL容器 類(lèi)可能為了使用一個(gè)特定類(lèi)型的數(shù)據(jù)而創(chuàng)建一個(gè)迭代器。作為指針,必須能夠使用* 操作符類(lèi)獲取數(shù)據(jù)。你還可以使用其他數(shù)學(xué)操作符如++。典型的,++操作符用來(lái)遞增 迭代器,以訪問(wèn)容器中的下一個(gè)對(duì)象。如果迭代器到達(dá)了容器中的最后一個(gè)元素的后 面,則迭代器變成past-the-end值。使用一個(gè)past-the-end值得指針來(lái)訪問(wèn)對(duì)象是非 法的,就好像使用NULL或?yàn)槌跏蓟闹羔樢粯印?br /> 提示
STL不保證可以從另一個(gè)迭代器來(lái)抵達(dá)一個(gè)迭代器。例如,當(dāng)對(duì)一個(gè)集合中的對(duì)象排 序時(shí),如果你在不同的結(jié)構(gòu)中指定了兩個(gè)迭代器,第二個(gè)迭代器無(wú)法從第一個(gè)迭代器 抵達(dá),此時(shí)程序注定要失敗。這是STL靈活性的一個(gè)代價(jià)。STL不保證檢測(cè)毫無(wú)道理的 錯(cuò)誤。
迭代器的類(lèi)型 對(duì)于STL數(shù)據(jù)結(jié)構(gòu)和算法,你可以使用五種迭代器。下面簡(jiǎn)要說(shuō)明了這五種類(lèi)型:
· Input iterators 提供對(duì)數(shù)據(jù)的只讀訪問(wèn)。
· Output iterators 提供對(duì)數(shù)據(jù)的只寫(xiě)訪問(wèn)
· Forward iterators 提供讀寫(xiě)操作,并能向前推進(jìn)迭代器。
· Bidirectional iterators提供讀寫(xiě)操作,并能向前和向后操作。
· Random access iterators提供讀寫(xiě)操作,并能在數(shù)據(jù)中隨機(jī)移動(dòng)。
盡管各種不同的STL實(shí)現(xiàn)細(xì)節(jié)方面有所不同,還是可以將上面的迭代器想象為一種類(lèi) 繼承關(guān)系。從這個(gè)意義上說(shuō),下面的迭代器繼承自上面的迭代器。由于這種繼承關(guān)系 ,你可以將一個(gè)Forward迭代器作為一個(gè)output或input迭代器使用。同樣,如果一個(gè) 算法要求是一個(gè)bidirectional 迭代器,那么只能使用該種類(lèi)型和隨機(jī)訪問(wèn)迭代器。
指針迭代器 正如下面的小程序顯示的,一個(gè)指針也是一種迭代器。該程序同樣顯示了STL的一個(gè) 主要特性——它不只是能夠用于它自己的類(lèi)類(lèi)型,而且也能用于任何C或C++類(lèi)型。Listi ng 1, iterdemo.cpp, 顯示了如何把指針作為迭代器用于STL的find()算法來(lái)搜索普通 的數(shù)組。
表 1. iterdemo.cpp
#i nclude <iostream.h> #i nclude <algorithm>
using namespace std;
#define SIZE 100 int iarray[SIZE];
int main() { iarray[20] = 50; int* ip = find(iarray, iarray + SIZE, 50); if (ip == iarray + SIZE) cout << "50 not found in array" << endl; else cout << *ip << " found in array" << endl; return 0; } 在引用了I/O流庫(kù)和STL算法頭文件(注意沒(méi)有.h后綴),該程序告訴編譯器使用std 名字空間。使用std名字空間的這行是可選的,因?yàn)榭梢詣h除該行對(duì)于這么一個(gè)小程 序來(lái)說(shuō)不會(huì)導(dǎo)致名字沖突。
程序中定義了尺寸為SIZE的全局?jǐn)?shù)組。由于是全局變量,所以運(yùn)行時(shí)數(shù)組自動(dòng)初始化 為零。下面的語(yǔ)句將在索引20位置處地元素設(shè)置為50,并使用find()算法來(lái)搜索值50 :
iarray[20] = 50; int* ip = find(iarray, iarray + SIZE, 50); find()函數(shù)接受三個(gè)參數(shù)。頭兩個(gè)定義了搜索的范圍。由于C和C++數(shù)組等同于指針, 表達(dá)式iarray指向數(shù)組的第一個(gè)元素。而第二個(gè)參數(shù)iarray + SIZE等同于past-the -end 值,也就是數(shù)組中最后一個(gè)元素的后面位置。第三個(gè)參數(shù)是待定位的值,也就 是50。find()函數(shù)返回和前兩個(gè)參數(shù)相同類(lèi)型的迭代器,這兒是一個(gè)指向整數(shù)的指針 ip。
提示
必須記住STL使用模板。因此,STL函數(shù)自動(dòng)根據(jù)它們使用的數(shù)據(jù)類(lèi)型來(lái)構(gòu)造。
為了判斷find()是否成功,例子中測(cè)***ip和 past-the-end 值是否相等:
if (ip == iarray + SIZE) ... 如果表達(dá)式為真,則表示在搜索的范圍內(nèi)沒(méi)有指定的值。否則就是指向一個(gè)合法對(duì)象 的指針,這時(shí)可以用下面的語(yǔ)句顯示::
cout << *ip << " found in array" << endl; 測(cè)***函數(shù)返回值和NULL是否相等是不正確的。不要象下面這樣使用:
int* ip = find(iarray, iarray + SIZE, 50); if (ip != NULL) ... // ??? incorrect 當(dāng)使用STL函數(shù)時(shí),只能測(cè)***ip是否和past-the-end 值是否相等。盡管在本例中ip是 一個(gè)C++指針,其用法也必須符合STL迭代器的規(guī)則。
容器迭代器 盡管C++指針也是迭代器,但用的更多的是容器迭代器。容器迭代器用法和iterdemo .cpp一樣,但和將迭代器申明為指針變量不同的是,你可以使用容器類(lèi)方法來(lái)獲取迭 代器對(duì)象。兩個(gè)典型的容器類(lèi)方法是begin()和end()。它們?cè)诖蠖鄶?shù)容器中表示整個(gè) 容器范圍。其他一些容器還使用rbegin()和rend()方法提供反向迭代器,以按反向順 序指定對(duì)象范圍。
下面的程序創(chuàng)建了一個(gè)矢量容器(STL的和數(shù)組等價(jià)的對(duì)象),并使用迭代器在其中 搜索。該程序和前一章中的程序相同。
Listing 2. vectdemo.cpp
#i nclude <iostream.h> #i nclude <algorithm> #i nclude <vector>
using namespace std;
vector<int> intVector(100);
void main() { intVector[20] = 50; vector<int>::iterator intIter = find(intVector.begin(), intVector.end(), 50); if (intIter != intVector.end()) cout << "Vector contains value " << *intIter << endl; else cout << "Vector does not contain 50" << endl; }
注意用下面的方法顯示搜索到的數(shù)據(jù):
cout << "Vector contains value " << *intIter << endl; 常量迭代器 和指針一樣,你可以給一個(gè)迭代器賦值。例如,首先申明一個(gè)迭代器:
vector<int>::iterator first; 該語(yǔ)句創(chuàng)建了一個(gè)vector<int>類(lèi)的迭代器。下面的語(yǔ)句將該迭代器設(shè)置到intVector 的第一個(gè)對(duì)象,并將它指向的對(duì)象值設(shè)置為123::
first = intVector.begin(); *first = 123; 這種賦值對(duì)于大多數(shù)容器類(lèi)都是允許的,除了只讀變量。為了防止錯(cuò)誤賦值,可以申 明迭代器為:
const vector<int>::iterator result; result = find(intVector.begin(), intVector.end(), value); if (result != intVector.end()) *result = 123; // ??? 警告
另一種防止數(shù)據(jù)被改變得方法是將容器申明為const類(lèi)型。
『呀!在VC中測(cè)***出錯(cuò),正確的含義是result成為常量而不是它指向的對(duì)象不允許改 變,如同int *const p;看來(lái)這作者自己也不懂』
使用迭代器編程 你已經(jīng)見(jiàn)到了迭代器的一些例子,現(xiàn)在我們將關(guān)注每種特定的迭代器如何使用。由于 使用迭代器需要關(guān)于STL容器類(lèi)和算法的知識(shí),在閱讀了后面的兩章后你可能需要重 新復(fù)習(xí)一下本章內(nèi)容。
輸入迭代器 輸入迭代器是最普通的類(lèi)型。輸入迭代器至少能夠使用==和!=測(cè)***是否相等;使用* 來(lái)訪問(wèn)數(shù)據(jù);使用++操作來(lái)遞推迭代器到下一個(gè)元素或到達(dá)past-the-end 值。
為了理解迭代器和STL函數(shù)是如何使用它們的,現(xiàn)在來(lái)看一下find()模板函數(shù)的定義 :
template <class InputIterator, class T> InputIterator find( InputIterator first, InputIterator last, const T& value) { while (first != last && *first != value) ++first; return first; }
注意
在find()算法中,注意如果first和last指向不同的容器,該算法可能陷入死循環(huán)。
輸出迭代器 輸出迭代器缺省只寫(xiě),通常用于將數(shù)據(jù)從一個(gè)位置拷貝到另一個(gè)位置。由于輸出迭代 器無(wú)法讀取對(duì)象,因此你不會(huì)在任何搜索和其他算法中使用它。要想讀取一個(gè)拷貝的 值,必須使用另一個(gè)輸入迭代器(或它的繼承迭代器)。
Listing 3. outiter.cpp
#i nclude <iostream.h> #i nclude <algorithm> // Need copy() #i nclude <vector> // Need vector
using namespace std;
double darray[10] = {1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9};
vector<double> vdouble(10);
int main() { vector<double>::iterator outputIterator = vdouble.begin(); copy(darray, darray + 10, outputIterator); while (outputIterator != vdouble.end()) { cout << *outputIterator << endl; outputIterator++; } return 0; } 注意
當(dāng)使用copy()算法的時(shí)候,你必須確保目標(biāo)容器有足夠大的空間,或者容器本身是自 動(dòng)擴(kuò)展的。
前推迭代器 前推迭代器能夠讀寫(xiě)數(shù)據(jù)值,并能夠向前推進(jìn)到下一個(gè)值。但是沒(méi)法遞減。replace ()算法顯示了前推迭代器的使用方法。
template <class ForwardIterator, class T> void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value); 使用replace()將[first,last]范圍內(nèi)的所有值為old_value的對(duì)象替換為new_value 。:
replace(vdouble.begin(), vdouble.end(), 1.5, 3.14159); 雙向迭代器 雙向迭代器要求能夠增減。如reverse()算法要求兩個(gè)雙向迭代器作為參數(shù):
template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last); 使用reverse()函數(shù)來(lái)對(duì)容器進(jìn)行逆向排序:
reverse(vdouble.begin(), vdouble.end()); 隨機(jī)訪問(wèn)迭代器 隨機(jī)訪問(wèn)迭代器能夠以任意順序訪問(wèn)數(shù)據(jù),并能用于讀寫(xiě)數(shù)據(jù)(不是const的C++指針 也是隨機(jī)訪問(wèn)迭代器)。STL的排序和搜索函數(shù)使用隨機(jī)訪問(wèn)迭代器。隨機(jī)訪問(wèn)迭代 器可以使用關(guān)系操作符作比較。
random_shuffle() 函數(shù)隨機(jī)打亂原先的順序。申明為:
template <class RandomAccessIterator> void random_shuffle (RandomAccessIterator first, RandomAccessIterator last); 使用方法:
random_shuffle(vdouble.begin(), vdouble.end()); 迭代器技術(shù) 要學(xué)會(huì)使用迭代器和容器以及算法,需要學(xué)習(xí)下面的新技術(shù)。
流和迭代器 本書(shū)的很多例子程序使用I/O流語(yǔ)句來(lái)讀寫(xiě)數(shù)據(jù)。例如:
int value; cout << "Enter value: "; cin >> value; cout << "You entered " << value << endl; 對(duì)于迭代器,有另一種方法使用流和標(biāo)準(zhǔn)函數(shù)。理解的要點(diǎn)是將輸入/輸出流作為容 器看待。因此,任何接受迭代器參數(shù)的算法都可以和流一起工作。
Listing 4. outstrm.cpp
#i nclude <iostream.h> #i nclude <stdlib.h> // Need random(), srandom() #i nclude <time.h> // Need time() #i nclude <algorithm> // Need sort(), copy() #i nclude <vector> // Need vector
using namespace std;
void Display(vector<int>& v, const char* s);
int main() { // Seed the random number generator srandom( time(NULL) );
// Construct vector and fill with random integer values vector<int> collection(10); for (int i = 0; i < 10; i++) collection[i] = random() % 10000;;
// Display, sort, and redisplay Display(collection, "Before sorting"); sort(collection.begin(), collection.end()); Display(collection, "After sorting"); return 0; }
// Display label s and contents of integer vector v void Display(vector<int>& v, const char* s) { cout << endl << s << endl; copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\t")); cout << endl; } 函數(shù)Display()顯示了如何使用一個(gè)輸出流迭代器。下面的語(yǔ)句將容器中的值傳輸?shù)?br />cout輸出流對(duì)象中:
copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\t")); 第三個(gè)參數(shù)實(shí)例化了ostream_iterator<int>類(lèi)型,并將它作為copy()函數(shù)的輸出目 標(biāo)迭代器對(duì)象。“\t”字符串是作為分隔符。運(yùn)行結(jié)果:
$ g++ outstrm.cpp $ ./a.out Before sorting 677 722 686 238 9*** 397 251 118 11 312 After sorting 11 118 238 251 312 397 677 686 722 9*** 這是STL神奇的一面『確實(shí)神奇』。為定義輸出流迭代器,STL提供了模板類(lèi)ostream_ite rator 。這個(gè)類(lèi)的構(gòu)造函數(shù)有兩個(gè)參數(shù):一個(gè)ostream對(duì)象和一個(gè)string值。因此可以象下 面一樣簡(jiǎn)單地創(chuàng)建一個(gè)迭代器對(duì)象:
ostream_iterator<int>(cout, "\n") 該迭代起可以和任何接受一個(gè)輸出迭代器的函數(shù)一起使用。
插入迭代器 插入迭代器用于將值插入到容器中。它們也叫做適配器,因?yàn)樗鼈儗⑷萜鬟m配或轉(zhuǎn)化 為一個(gè)迭代器,并用于copy()這樣的算法中。例如,一個(gè)程序定義了一個(gè)鏈表和一個(gè) 矢量容器:
list<double> dList; vector<double> dVector; 通過(guò)使用front_inserter迭代器對(duì)象,可以只用單個(gè)copy()語(yǔ)句就完成將矢量中的對(duì) 象插入到鏈表前端的操作:
copy(dVector.begin(), dVector.end(), front_inserter(dList)); 三種插入迭代器如下:
· 普通插入器 將對(duì)象插入到容器任何對(duì)象的前面。
· Front inserters 將對(duì)象插入到數(shù)據(jù)集的前面——例如,鏈表表頭。
· Back inserters 將對(duì)象插入到集合的尾部——例如,矢量的尾部,導(dǎo)致 矢量容器擴(kuò)展。
使用插入迭代器可能導(dǎo)致容器中的其他對(duì)象移動(dòng)位置,因而使得現(xiàn)存的迭代器非法。 例如,將一個(gè)對(duì)象插入到矢量容器將導(dǎo)致其他值移動(dòng)位置以騰出空間。一般來(lái)說(shuō),插 入到象鏈表這樣的結(jié)構(gòu)中更為有效,因?yàn)樗鼈儾粫?huì)導(dǎo)致其他對(duì)象移動(dòng)。
Listing 5. insert.cpp
#i nclude <iostream.h> #i nclude <algorithm> #i nclude <list>
using namespace std;
int iArray[5] = { 1, 2, 3, 4, 5 };
void Display(list<int>& v, const char* s);
int main() { list<int> iList;
// Copy iArray backwards into iList copy(iArray, iArray + 5, front_inserter(iList)); Display(iList, "Before find and copy");
// Locate value 3 in iList list<int>::iterator p = find(iList.begin(), iList.end(), 3);
// Copy first two iArray values to iList ahead of p copy(iArray, iArray + 2, inserter(iList, p)); Display(iList, "After find and copy");
return 0; }
void Display(list<int>& a, const char* s) { cout << s << endl; copy(a.begin(), a.end(), ostream_iterator<int>(cout, " ")); cout << endl; } 運(yùn)行結(jié)果如下:
$ g++ insert.cpp $ ./a.out Before find and copy 5 4 3 2 1 After find and copy 5 4 1 2 3 2 1 可以將front_inserter替換為back_inserter******。
如果用find()去查找在列表中不存在的值,例如99。由于這時(shí)將p設(shè)置為past-the-end 值。最后的copy()函數(shù)將iArray的值附加到鏈表的后部。
混合迭代器函數(shù) 在涉及到容器和算法的操作中,還有兩個(gè)迭代器函數(shù)非常有用:
· advance() 按指定的數(shù)目增減迭代器。
· distance() 返回到達(dá)一個(gè)迭代器所需(遞增)操作的數(shù)目。
例如:
list<int> iList; list<int>::iterator p = find(iList.begin(), iList.end(), 2); cout << "before: p == " << *p << endl; advance(p, 2); // same as p = p + 2; cout << "after : p == " << *p << endl;
int k = 0; distance(p, iList.end(), k); cout << "k == " << k << endl;
advance()函數(shù)接受兩個(gè)參數(shù)。第二個(gè)參數(shù)是向前推進(jìn)的數(shù)目。對(duì)于前推迭代器,該 值必須為正,而對(duì)于雙向迭代器和隨機(jī)訪問(wèn)迭代器,該值可以為負(fù)。
使用 distance()函數(shù)來(lái)返回到達(dá)另一個(gè)迭代器所需要的步驟。 注意
distance()函數(shù)是迭代的,也就是說(shuō),它遞增第三個(gè)參數(shù)。因此,你必須初始化該參 數(shù)。未初始化該參數(shù)幾乎注定要失敗。
函數(shù)和函數(shù)對(duì)象 STL中,函數(shù)被稱(chēng)為算法,也就是說(shuō)它們和標(biāo)準(zhǔn)C庫(kù)函數(shù)相比,它們更為通用。STL算 法通過(guò)重載operator()函數(shù)實(shí)現(xiàn)為模板類(lèi)或模板函數(shù)。這些類(lèi)用于創(chuàng)建函數(shù)對(duì)象,對(duì) 容器中的數(shù)據(jù)進(jìn)行各種各樣的操作。下面的幾節(jié)解釋如何使用函數(shù)和函數(shù)對(duì)象。
函數(shù)和斷言 經(jīng)常需要對(duì)容器中的數(shù)據(jù)進(jìn)行用戶(hù)自定義的操作。例如,你可能希望遍歷一個(gè)容器中 所有對(duì)象的STL算法能夠回調(diào)自己的函數(shù)。例如
#i nclude <iostream.h> #i nclude <stdlib.h> // Need random(), srandom() #i nclude <time.h> // Need time() #i nclude <vector> // Need vector #i nclude <algorithm> // Need for_each()
#define VSIZE 24 // Size of vector vector<long> v(VSIZE); // Vector object
// Function prototypes void initialize(long &ri); void show(const long &ri); bool isMinus(const long &ri); // Predicate function
int main() { srandom( time(NULL) ); // Seed random generator
for_each(v.begin(), v.end(), initialize);//調(diào)用普通函數(shù) cout << "Vector of signed long integers" << endl; for_each(v.begin(), v.end(), show); cout << endl;
// Use predicate function to count negative values // int count = 0; vector<long>::iterator p; p = find_if(v.begin(), v.end(), isMinus);//調(diào)用斷言函數(shù) while (p != v.end()) { count++; p = find_if(p + 1, v.end(), isMinus); } cout << "Number of values: " << VSIZE << endl; cout << "Negative values : " << count << endl;
return 0; }
// Set ri to a signed integer value void initialize(long &ri) { ri = ( random() - (RAND_MAX / 2) ); // ri = random(); }
// Display value of ri void show(const long &ri) { cout << ri << " "; }
// Returns true if ri is less than 0 bool isMinus(const long &ri) { return (ri < 0); }
所謂斷言函數(shù),就是返回bool值的函數(shù)。
函數(shù)對(duì)象 除了給STL算法傳遞一個(gè)回調(diào)函數(shù),你還可能需要傳遞一個(gè)類(lèi)對(duì)象以便執(zhí)行更復(fù)雜的 操作。這樣的一個(gè)對(duì)象就叫做函數(shù)對(duì)象。實(shí)際上函數(shù)對(duì)象就是一個(gè)類(lèi),但它和回調(diào)函 數(shù)一樣可以被回調(diào)。例如,在函數(shù)對(duì)象每次被for_each()或find_if()函數(shù)調(diào)用時(shí)可 以保留統(tǒng)計(jì)信息。函數(shù)對(duì)象是通過(guò)重載operator()()實(shí)現(xiàn)的。如果TanyClass定義了 opeator()(),那么就可以這么使用:
TAnyClass object; // Construct object object(); // Calls TAnyClass::operator()() function for_each(v.begin(), v.end(), object); STL定義了幾個(gè)函數(shù)對(duì)象。由于它們是模板,所以能夠用于任何類(lèi)型,包括C/C++固有 的數(shù)據(jù)類(lèi)型,如long。有些函數(shù)對(duì)象從名字中就可以看出它的用途,如plus()和multipl ies ()。類(lèi)似的greater()和less-equal()用于比較兩個(gè)值。
注意
有些版本的ANSI C++定義了times()函數(shù)對(duì)象,而GNU C++把它命名為multiplies()。 使用時(shí)必須包含頭文件<functional>。
一個(gè)有用的函數(shù)對(duì)象的應(yīng)用是accumulate() 算法。該函數(shù)計(jì)算容器中所有值的總和 。記住這樣的值不一定是簡(jiǎn)單的類(lèi)型,通過(guò)重載operator+(),也可以是類(lèi)對(duì)象。
Listing 8. accum.cpp
#i nclude <iostream.h> #i nclude <numeric> // Need accumulate() #i nclude <vector> // Need vector #i nclude <functional> // Need multiplies() (or times())
#define MAX 10 vector<long> v(MAX); // Vector object
int main() { // Fill vector using conventional loop // for (int i = 0; i < MAX; i++) v[i] = i + 1;
// Accumulate the sum of contained values // long sum = accumulate(v.begin(), v.end(), 0); cout << "Sum of values == " << sum << endl;
// Accumulate the product of contained values // long product = accumulate(v.begin(), v.end(), 1, multiplies<long>());//注意這行 cout << "Product of values == " << product << endl;
return 0; } 編譯輸出如下:
$ g++ accum.cpp $ ./a.out Sum of values == 55 Product of values == 3628800 『注意使用了函數(shù)對(duì)象的accumulate()的用法。accumulate() 在內(nèi)部將每個(gè)容器中 的對(duì)象和第三個(gè)參數(shù)作為multiplies函數(shù)對(duì)象的參數(shù),multiplies(1,v)計(jì)算乘積。VC 中的這些模板的源代碼如下:
// TEMPLATE FUNCTION accumulate
template<class _II, class _Ty> inline
_Ty accumulate(_II _F, _II _L, _Ty _V)
{for (; _F != _L; ++_F)
_V = _V + *_F;
return (_V); }
// TEMPLATE FUNCTION accumulate WITH BINOP
template<class _II, class _Ty, class _Bop> inline
_Ty accumulate(_II _F, _II _L, _Ty _V, _Bop _B)
{for (; _F != _L; ++_F)
_V = _B(_V, *_F);
return (_V); }
// TEMPLATE STRUCT binary_function
template<class _A1, class _A2, class _R>
struct binary_function {
typedef _A1 first_argument_type;
typedef _A2 second_argument_type;
typedef _R result_type;
};
// TEMPLATE STRUCT multiplies
template<class _Ty>
struct multiplies : binary_function<_Ty, _Ty, _Ty> {
_Ty operator()(const _Ty& _X, const _Ty& _Y) const
{return (_X * _Y); }
};
引言:如果你想深入了解STL到底是怎么實(shí)現(xiàn)的,最好的辦法是寫(xiě)個(gè)簡(jiǎn)單的程序,將 程序中涉及到的模板源碼給copy下來(lái),稍作整理,就能看懂了。所以沒(méi)有必要去買(mǎi)什 么《STL源碼剖析》之類(lèi)的書(shū)籍,那些書(shū)可能反而浪費(fèi)時(shí)間。』
發(fā)生器函數(shù)對(duì)象 有一類(lèi)有用的函數(shù)對(duì)象是“發(fā)生器”(generator)。這類(lèi)函數(shù)有自己的內(nèi)存,也就是 說(shuō)它能夠從先前的調(diào)用中記住一個(gè)值。例如隨機(jī)數(shù)發(fā)生器函數(shù)。
普通的C程序員使用靜態(tài)或全局變量 “記憶”上次調(diào)用的結(jié)果。但這樣做的缺點(diǎn)是該 函數(shù)無(wú)法和它的數(shù)據(jù)相分離『還有個(gè)缺點(diǎn)是要用TLS才能線程安全』。顯然,使用類(lèi) 來(lái)封裝一塊:“內(nèi)存”更安全可靠。先看一下例子:
Listing 9. randfunc.cpp
#i nclude <iostream.h> #i nclude <stdlib.h> // Need random(), srandom() #i nclude <time.h> // Need time() #i nclude <algorithm> // Need random_shuffle() #i nclude <vector> // Need vector #i nclude <functional> // Need ptr_fun()
using namespace std;
// Data to randomize int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; vector<int> v(iarray, iarray + 10);
// Function prototypes void Display(vector<int>& vr, const char *s); unsigned int RandInt(const unsigned int n);
int main() { srandom( time(NULL) ); // Seed random generator Display(v, "Before shuffle:");
pointer_to_unary_function<unsigned int, unsigned int> ptr_RandInt = ptr_fun(RandInt); // Pointer to RandInt()//注意這行 random_shuffle(v.begin(), v.end(), ptr_RandInt);
Display(v, "After shuffle:"); return 0; }
// Display contents of vector vr void Display(vector<int>& vr, const char *s) { cout << endl << s << endl; copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " ")); cout << endl; }
// Return next random value in sequence modulo n unsigned int RandInt(const unsigned int n) { return random() % n; } 編譯運(yùn)行結(jié)果如下:
$ g++ randfunc.cpp $ ./a.out Before shuffle: 1 2 3 4 5 6 7 8 9 10 After shuffle: 6 7 2 8 3 5 10 1 9 4 首先用下面的語(yǔ)句申明一個(gè)對(duì)象:
pointer_to_unary_function<unsigned int, unsigned int> ptr_RandInt = ptr_fun(RandInt); 這兒使用STL的單目函數(shù)模板定義了一個(gè)變量ptr_RandInt,并將地址初始化到我們的 函數(shù)RandInt()。單目函數(shù)接受一個(gè)參數(shù),并返回一個(gè)值。現(xiàn)在random_shuffle()可 以如下調(diào)用:
random_shuffle(v.begin(), v.end(), ptr_RandInt); 在本例子中,發(fā)生器只是簡(jiǎn)單的調(diào)用rand()函數(shù)。
關(guān)于常量引用的一點(diǎn)小麻煩(不翻譯了,VC下將例子中的const去掉)
發(fā)生器函數(shù)類(lèi)對(duì)象 下面的例子說(shuō)明發(fā)生器函數(shù)類(lèi)對(duì)象的使用。
Listing 10. fiborand.cpp
#i nclude <iostream.h> #i nclude <algorithm> // Need random_shuffle() #i nclude <vector> // Need vector #i nclude <functional> // Need unary_function
using namespace std;
// Data to randomize int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; vector<int> v(iarray, iarray + 10);
// Function prototype void Display(vector<int>& vr, const char *s);
// The FiboRand template function-object class template <class Arg> class FiboRand : public unary_function<Arg, Arg> { int i, j; Arg sequence[18]; public: FiboRand(); Arg operator()(const Arg& arg); };
void main() { FiboRand<int> fibogen; // Construct generator object cout << "Fibonacci random number generator" << endl; cout << "using random_shuffle and a function object" << endl; Display(v, "Before shuffle:"); random_shuffle(v.begin(), v.end(), fibogen); Display(v, "After shuffle:"); }
// Display contents of vector vr void Display(vector<int>& vr, const char *s) { cout << endl << s << endl; copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " ")); cout << endl; }
// FiboRand class constructor template<class Arg> FiboRand<Arg>::FiboRand() { sequence[17] = 1; sequence[16] = 2; for (int n = 15; n > 0; n—) sequence[n] = sequence[n + 1] + sequence[n + 2]; i = 17; j = 5; }
// FiboRand class function operator template<class Arg> Arg FiboRand<Arg>::operator()(const Arg& arg) { Arg k = sequence[i] + sequence[j]; sequence[i] = k; i--; j--; if (i == 0) i = 17; if (j == 0) j = 17; return k % arg; } 編譯運(yùn)行輸出如下:
$ g++ fiborand.cpp $ ./a.out Fibonacci random number generator using random_shuffle and a function object Before shuffle: 1 2 3 4 5 6 7 8 9 10 After shuffle: 6 8 5 4 3 7 10 1 9 該程序用完全不通的方法使用使用rand_shuffle。Fibonacci 發(fā)生器封裝在一個(gè)類(lèi)中 ,該類(lèi)能從先前的“使用”中記憶運(yùn)行結(jié)果。在本例中,類(lèi)FiboRand 維護(hù)了一個(gè)數(shù) 組和兩個(gè)索引變量I和j。
FiboRand類(lèi)繼承自u(píng)nary_function() 模板:
template <class Arg> class FiboRand : public unary_function<Arg, Arg> {... Arg是用戶(hù)自定義數(shù)據(jù)類(lèi)型。該類(lèi)還定以了兩個(gè)成員函數(shù),一個(gè)是構(gòu)造函數(shù),另一個(gè) 是operator()()函數(shù),該操作符允許random_shuffle()算法象一個(gè)函數(shù)一樣“調(diào)用 ”一個(gè)FiboRand對(duì)象。
綁定器函數(shù)對(duì)象 一個(gè)綁定器使用另一個(gè)函數(shù)對(duì)象f()和參數(shù)值V創(chuàng)建一個(gè)函數(shù)對(duì)象。被綁定函數(shù)對(duì)象必 須為雙目函數(shù),也就是說(shuō)有兩個(gè)參數(shù),A和B。STL 中的幫定器有:
· bind1st() 創(chuàng)建一個(gè)函數(shù)對(duì)象,該函數(shù)對(duì)象將值V作為第一個(gè)參數(shù)A。
· bind2nd()創(chuàng)建一個(gè)函數(shù)對(duì)象,該函數(shù)對(duì)象將值V作為第二個(gè)參數(shù)B。
舉例如下:
Listing 11. binder.cpp
#i nclude <iostream.h> #i nclude <algorithm> #i nclude <functional> #i nclude <list>
using namespace std;
// Data int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; list<int> aList(iarray, iarray + 10);
int main() { int k = 0; count_if(aList.begin(), aList.end(), bind1st(greater<int>(), 8), k); cout << "Number elements < 8 == " << k << endl; return 0; } Algorithm count_if()計(jì)算滿(mǎn)足特定條件的元素的數(shù)目。 這是通過(guò)將一個(gè)函數(shù)對(duì)象 和一個(gè)參數(shù)捆綁到為一個(gè)對(duì)象,并將該對(duì)象作為算法的第三個(gè)參數(shù)實(shí)現(xiàn)的。 注意這 個(gè)表達(dá)式:
bind1st(greater<int>(), 8) 該表達(dá)式將greater<int>()和一個(gè)參數(shù)值8捆綁為一個(gè)函數(shù)對(duì)象。由于使用了bind1st (),所以該函數(shù)相當(dāng)于計(jì)算下述表達(dá)式:
8 > q 表達(dá)式中的q是容器中的對(duì)象。因此,完整的表達(dá)式
count_if(aList.begin(), aList.end(), bind1st(greater<int>(), 8), k); 計(jì)算所有小于或等于8的對(duì)象的數(shù)目。
否定函數(shù)對(duì)象 所謂否定(negator)函數(shù)對(duì)象,就是它從另一個(gè)函數(shù)對(duì)象創(chuàng)建而來(lái),如果原先的函數(shù) 返回真,則否定函數(shù)對(duì)象返回假。有兩個(gè)否定函數(shù)對(duì)象:not1()和not2()。not1()接 受單目函數(shù)對(duì)象,not2()接受雙目函數(shù)對(duì)象。否定函數(shù)對(duì)象通常和幫定器一起使用。 例如,上節(jié)中用bind1nd來(lái)搜索q<=8的值:
count_if(aList.begin(), aList.end(), bind1st(greater<int>(), 8), k); 如果要搜索q>8的對(duì)象,則用bind2st。而現(xiàn)在可以這樣寫(xiě):
start = find_if(aList.begin(), aList.end(), not1(bind1nd(greater<int>(), 6))); 你必須使用not1,因?yàn)閎ind1nd返回單目函數(shù)。
總結(jié):使用標(biāo)準(zhǔn)模板庫(kù) (STL) 盡管很多程序員仍然在使用標(biāo)準(zhǔn)C函數(shù),但是這就好像騎著毛驢尋找Mercedes一樣。 你當(dāng)然最終也會(huì)到達(dá)目標(biāo),但是你浪費(fèi)了很多時(shí)間。
盡管有時(shí)候使用標(biāo)準(zhǔn)C函數(shù)確實(shí)方便(如使用sprintf()進(jìn)行格式化輸出)。但是C函數(shù) 不使用異常機(jī)制來(lái)報(bào)告錯(cuò)誤,也不適合處理新的數(shù)據(jù)類(lèi)型。而且標(biāo)準(zhǔn)C函數(shù)經(jīng)常使用 內(nèi)存分配技術(shù),沒(méi)有經(jīng)驗(yàn)的程序員很容易寫(xiě)出bug來(lái)。.
C++標(biāo)準(zhǔn)庫(kù)則提供了更為安全,更為靈活的數(shù)據(jù)集處理方式。STL最初由HP實(shí)驗(yàn)室的Alexa nder Stepanov和Meng Lee開(kāi)發(fā)。最近,C++標(biāo)準(zhǔn)委員會(huì)采納了STL,盡管在不同的實(shí)現(xiàn)之 間仍有細(xì)節(jié)差別。
STL的最主要的兩個(gè)特點(diǎn):數(shù)據(jù)結(jié)構(gòu)和算法的分離,非面向?qū)ο蟊举|(zhì)。訪問(wèn)對(duì)象是通 過(guò)象指針一樣的迭代器實(shí)現(xiàn)的;容器是象鏈表,矢量之類(lèi)的數(shù)據(jù)結(jié)構(gòu),并按模板方式 提供;算法是函數(shù)模板,用于操作容器中的數(shù)據(jù)。由于STL以模板為基礎(chǔ),所以能用 于任何數(shù)據(jù)類(lèi)型和結(jié)構(gòu)。
-- |