STL的一個重要特色是數據結構和算法的分離。儘管這是個簡單的概念,但這種分離確實使得STL變得很是通用。例如,因爲STL的sort()函數是徹底通用的,你能夠用它來操做幾乎任何數據集合,包括鏈表,容器和數組。前端
STL算法做爲模板函數提供。爲了和其餘組件相區別,在本書中STL算法之後接一對圓括弧的方式表示,例如sort()。ios
STL另外一個重要特性是它不是面向對象的。爲了具備足夠通用性,STL主要依賴於模板而不是封裝,繼承和虛函數(多態性)——OOP的三個要素。你在STL中找不到任何明顯的類繼承關係。這好像是一種倒退,但這正好是使得STL的組件具備普遍通用性的底層特徵。另外,因爲STL是基於模板,內聯函數的使用使得生成的代碼短小高效。程序員
提示redis
確保在編譯使用了STL的程序中至少要使用-O優化來保證內聯擴展。STL提供了大量的模板類和函數,能夠在OOP和常規編程中使用。全部的STL的大約50個算法都是徹底通用的,並且不依賴於任何特定的數據類型。下面的小節說明了三個基本的STL組件:算法
1) 迭代器提供了訪問容器中對象的方法。例如,可使用一對迭代器指定list或vector中的必定範圍的對象。迭代器就如同一個指針。事實上,C++的指針也是一種迭代器。可是,迭代器也能夠是那些定義了operator*()以及其餘相似於指針的操做符地方法的類對象。編程
2) 容器是一種數據結構,如list,vector,和deques ,以模板類的方法提供。爲了訪問容器中的數據,可使用由容器類輸出的迭代器。小程序
3) 算法是用來操做容器中的數據的模板函數。例如,STL用sort()來對一個vector中的數據進行排序,用find()來搜索一個list中的對象。函數自己與他們操做的數據的結構和類型無關,所以他們能夠在從簡單數組到高度複雜容器的任何數據結構上使用。數組
爲了不和其餘頭文件衝突, STL的頭文件再也不使用常規的.h擴展。爲了包含標準的string類,迭代器和算法,用下面的指示符:安全
#include <string> #include <iterator> #include <algorithm>
若是你查看STL的頭文件,你能夠看到象iterator.h和stl_iterator.h這樣的頭文件。因爲這些名字在各類STL實現之間均可能不一樣,你應該避免使用這些名字來引用這些頭文件。爲了確保可移植性,使用相應的沒有.h後綴的文件名。表1列出了最常使用的各類容器類的頭文件。該表並不完整,對於其餘頭文件,我將在本章和後面的兩章中介紹。數據結構
表 1. STL頭文件和容器類
#include |
Container Class |
<deque> |
deque |
<list> |
list |
<map> |
map, multimap |
<queue> |
queue, priority_queue |
<set> |
set, multiset |
<stack> |
stack |
<vector> |
vector, vector<bool> |
你的編譯器可能不能識別名字空間。名字空間就好像一個信封,將標誌符封裝在另外一個名字中。標誌符只在名字空間中存在,於是避免了和其餘標誌符衝突。例如,可能有其餘庫和程序模塊定義了sort()函數,爲了不和STL地sort()算法衝突,STL的sort()以及其餘標誌符都封裝在名字空間std中。STL的sort()算法編譯爲std::sort(),從而避免了名字衝突。
儘管你的編譯器可能沒有實現名字空間,你仍然可使用他們。爲了使用STL,能夠將下面的指示符插入到你的源代碼文件中,典型地是在全部的#include指示符的後面:
using namespace std;
迭代器提供對一個容器中的對象的訪問方法,而且定義了容器中對象的範圍。迭代器就如同一個指針。事實上,C++的指針也是一種迭代器。可是,迭代器不只僅是指針,所以你不能認爲他們必定具備地址值。例如,一個數組索引,也能夠認爲是一種迭代器。
迭代器有各類不一樣的建立方法。程序可能把迭代器做爲一個變量建立。一個STL容器類可能爲了使用一個特定類型的數據而建立一個迭代器。做爲指針,必須可以使用*操做符類獲取數據。你還可使用其餘數學操做符如++。典型的,++操做符用來遞增迭代器,以訪問容器中的下一個對象。若是迭代器到達了容器中的最後一個元素的後面,則迭代器變成past-the-end值。使用一個past-the-end值得指針來訪問對象是非法的,就好像使用NULL或爲初始化的指針同樣。
提示
STL不保證能夠從另外一個迭代器來抵達一個迭代器。例如,當對一個集合中的對象排序時,若是你在不一樣的結構中指定了兩個迭代器,第二個迭代器沒法從第一個迭代器抵達,此時程序註定要失敗。這是STL靈活性的一個代價。STL不保證檢測毫無道理的錯誤。
對於STL數據結構和算法,你可使用五種迭代器。下面簡要說明了這五種類型:
儘管各類不一樣的STL實現細節方面有所不一樣,仍是能夠將上面的迭代器想象爲一種類繼承關係。從這個意義上說,下面的迭代器繼承自上面的迭代器。因爲這種繼承關係,你能夠將一個Forward迭代器做爲一個output或input迭代器使用。一樣,若是一個算法要求是一個bidirectional 迭代器,那麼只能使用該種類型和隨機訪問迭代器。
正以下面的小程序顯示的,一個指針也是一種迭代器。該程序一樣顯示了STL的一個主要特性——它不僅是可以用於它本身的類類型,並且也能用於任何C或C++類型。Listing 1, iterdemo.cpp, 顯示瞭如何把指針做爲迭代器用於STL的find()算法來搜索普通的數組。
表 1. iterdemo.cpp
#include <iostream.h> #include <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流庫和STL算法頭文件(注意沒有.h後綴),該程序告訴編譯器使用std名字空間。使用std名字空間的這行是可選的,由於能夠刪除該行對於這麼一個小程序來講不會致使名字衝突。
程序中定義了尺寸爲SIZE的全局數組。因爲是全局變量,因此運行時數組自動初始化爲零。下面的語句將在索引20位置處地元素設置爲50,並使用find()算法來搜索值50:
iarray[20] = 50; int* ip = find(iarray, iarray + SIZE, 50);
find()函數接受三個參數。頭兩個定義了搜索的範圍。因爲C和C++數組等同於指針,表達式iarray指向數組的第一個元素。而第二個參數iarray + SIZE等同於past-the-end 值,也就是數組中最後一個元素的後面位置。第三個參數是待定位的值,也就是50。find()函數返回和前兩個參數相同類型的迭代器,這兒是一個指向整數的指針ip。
提示
必須記住STL使用模板。所以,STL函數自動根據它們使用的數據類型來構造。
爲了判斷find()是否成功,例子中測試ip和 past-the-end 值是否相等:
if (ip == iarray + SIZE) ...
若是表達式爲真,則表示在搜索的範圍內沒有指定的值。不然就是指向一個合法對象的指針,這時能夠用下面的語句顯示::
cout << *ip << " found in array" << endl;
測試函數返回值和NULL是否相等是不正確的。不要象下面這樣使用:
int* ip = find(iarray, iarray + SIZE, 50); if (ip != NULL) ... // ??? incorrect
當使用STL函數時,只能測試ip是否和past-the-end 值是否相等。儘管在本例中ip是一個C++指針,其用法也必須符合STL迭代器的規則。
儘管C++指針也是迭代器,但用的更多的是容器迭代器。容器迭代器用法和iterdemo.cpp同樣,但和將迭代器申明爲指針變量不一樣的是,你可使用容器類方法來獲取迭代器對象。兩個典型的容器類方法是begin()和end()。它們在大多數容器中表示整個容器範圍。其餘一些容器還使用rbegin()和rend()方法提供反向迭代器,以按反向順序指定對象範圍。
下面的程序建立了一個矢量容器(STL的和數組等價的對象),並使用迭代器在其中搜索。該程序和前一章中的程序相同。
Listing 2. vectdemo.cpp
#include <iostream.h> #include <algorithm> #include <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; }
注意用下面的方法顯示搜索到的數據:
cout << "Vector contains value " << *intIter << endl;
和指針同樣,你能夠給一個迭代器賦值。例如,首先申明一個迭代器:
vector<int>::iterator first;
該語句建立了一個vector<int>類的迭代器。下面的語句將該迭代器設置到intVector的第一個對象,並將它指向的對象值設置爲123::
first = intVector.begin(); *first = 123;
這種賦值對於大多數容器類都是容許的,除了只讀變量。爲了防止錯誤賦值,能夠申明迭代器爲:
const vector<int>::iterator result; result = find(intVector.begin(), intVector.end(), value); if (result != intVector.end()) *result = 123; // ???
警告
另外一種防止數據被改變得方法是將容器申明爲const類型。
『呀!在VC中測試出錯,正確的含義是result成爲常量而不是它指向的對象不容許改變,如同int *const p;看來這做者本身也不懂』
你已經見到了迭代器的一些例子,如今咱們將關注每種特定的迭代器如何使用。因爲使用迭代器須要關於STL容器類和算法的知識,在閱讀了後面的兩章後你可能須要從新複習一下本章內容。
輸入迭代器是最普通的類型。輸入迭代器至少可以使用==和!=測試是否相等;使用*來訪問數據;使用++操做來遞推迭代器到下一個元素或到達past-the-end 值。
爲了理解迭代器和STL函數是如何使用它們的,如今來看一下find()模板函數的定義:
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指向不一樣的容器,該算法可能陷入死循環。
輸出迭代器缺省只寫,一般用於將數據從一個位置拷貝到另外一個位置。因爲輸出迭代器沒法讀取對象,所以你不會在任何搜索和其餘算法中使用它。要想讀取一個拷貝的值,必須使用另外一個輸入迭代器(或它的繼承迭代器)。
Listing 3. outiter.cpp
#include <iostream.h> #include <algorithm> // Need copy() #include <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; }
注意
當使用copy()算法的時候,你必須確保目標容器有足夠大的空間,或者容器自己是自動擴展的。
前推迭代器可以讀寫數據值,並可以向前推動到下一個值。可是無法遞減。replace()算法顯示了前推迭代器的使用方法。
template <class ForwardIterator, class T> void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value);
使用replace()將[first,last]範圍內的全部值爲old_value的對象替換爲new_value。:
replace(vdouble.begin(), vdouble.end(), 1.5, 3.14159);
雙向迭代器要求可以增減。如reverse()算法要求兩個雙向迭代器做爲參數:
template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last);
使用reverse()函數來對容器進行逆向排序:
reverse(vdouble.begin(), vdouble.end());
隨機訪問迭代器可以以任意順序訪問數據,並能用於讀寫數據(不是const的C++指針也是隨機訪問迭代器)。STL的排序和搜索函數使用隨機訪問迭代器。隨機訪問迭代器可使用關係操做符做比較。
random_shuffle() 函數隨機打亂原先的順序。申明爲:
template <class RandomAccessIterator> void random_shuffle (RandomAccessIterator first, RandomAccessIterator last);
使用方法:
random_shuffle(vdouble.begin(), vdouble.end());
要學會使用迭代器和容器以及算法,須要學習下面的新技術。
本書的不少例子程序使用I/O流語句來讀寫數據。例如:
int value; cout << "Enter value: "; cin >> value; cout << "You entered " << value << endl;
對於迭代器,有另外一種方法使用流和標準函數。理解的要點是將輸入/輸出流做爲容器看待。所以,任何接受迭代器參數的算法均可以和流一塊兒工做。
Listing 4. outstrm.cpp
#include <iostream.h> #include <stdlib.h> // Need random(), srandom() #include <time.h> // Need time() #include <algorithm> // Need sort(), copy() #include <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; }
函數Display()顯示瞭如何使用一個輸出流迭代器。下面的語句將容器中的值傳輸到cout輸出流對象中:
copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\t"));
第三個參數實例化了ostream_iterator<int>類型,並將它做爲copy()函數的輸出目標迭代器對象。「\t」字符串是做爲分隔符。運行結果:
$ g++ outstrm.cpp
$ ./a.out
Before sorting
677 722 686 238 964 397 251 118 11 312
After sorting
11 118 238 251 312 397 677 686 722 964
這是STL神奇的一面『確實神奇』。爲定義輸出流迭代器,STL提供了模板類ostream_iterator。這個類的構造函數有兩個參數:一個ostream對象和一個string值。所以能夠象下面同樣簡單地建立一個迭代器對象:
ostream_iterator<int>(cout, "\n")
該迭代起能夠和任何接受一個輸出迭代器的函數一塊兒使用。
插入迭代器用於將值插入到容器中。它們也叫作適配器,由於它們將容器適配或轉化爲一個迭代器,並用於copy()這樣的算法中。例如,一個程序定義了一個鏈表和一個矢量容器:
list<double> dList; vector<double> dVector;
經過使用front_inserter迭代器對象,能夠只用單個copy()語句就完成將矢量中的對象插入到鏈表前端的操做:
copy(dVector.begin(), dVector.end(), front_inserter(dList));
三種插入迭代器以下:
使用插入迭代器可能致使容器中的其餘對象移動位置,於是使得現存的迭代器非法。例如,將一個對象插入到矢量容器將致使其餘值移動位置以騰出空間。通常來講,插入到象鏈表這樣的結構中更爲有效,由於它們不會致使其餘對象移動。
Listing 5. insert.cpp
#include <iostream.h> #include <algorithm> #include <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; }
運行結果以下:
$ 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。因爲這時將p設置爲past-the-end 值。最後的copy()函數將iArray的值附加到鏈表的後部。
在涉及到容器和算法的操做中,還有兩個迭代器函數很是有用:
例如:
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()函數接受兩個參數。第二個參數是向前推動的數目。對於前推迭代器,該值必須爲正,而對於雙向迭代器和隨機訪問迭代器,該值能夠爲負。
使用 distance()函數來返回到達另外一個迭代器所須要的步驟。
注意
distance()函數是迭代的,也就是說,它遞增第三個參數。所以,你必須初始化該參數。未初始化該參數幾乎註定要失敗。
STL中,函數被稱爲算法,也就是說它們和標準C庫函數相比,它們更爲通用。STL算法經過重載operator()函數實現爲模板類或模板函數。這些類用於建立函數對象,對容器中的數據進行各類各樣的操做。下面的幾節解釋如何使用函數和函數對象。
常常須要對容器中的數據進行用戶自定義的操做。例如,你可能但願遍歷一個容器中全部對象的STL算法可以回調本身的函數。例如
#include <iostream.h> #include <stdlib.h> // Need random(), srandom() #include <time.h> // Need time() #include <vector> // Need vector #include <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);//調用普通函數 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);//調用斷言函數 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); }
所謂斷言函數,就是返回bool值的函數。
除了給STL算法傳遞一個回調函數,你還可能須要傳遞一個類對象以便執行更復雜的操做。這樣的一個對象就叫作函數對象。實際上函數對象就是一個類,但它和回調函數同樣能夠被回調。例如,在函數對象每次被for_each()或find_if()函數調用時能夠保留統計信息。函數對象是經過重載operator()()實現的。若是TanyClass定義了opeator()(),那麼就能夠這麼使用:
TAnyClass object; // Construct object object(); // Calls TAnyClass::operator()() function for_each(v.begin(), v.end(), object);
STL定義了幾個函數對象。因爲它們是模板,因此可以用於任何類型,包括C/C++固有的數據類型,如long。有些函數對象從名字中就能夠看出它的用途,如plus()和multiplies()。相似的greater()和less-equal()用於比較兩個值。
注意
有些版本的ANSI C++定義了times()函數對象,而GNU C++把它命名爲multiplies()。使用時必須包含頭文件<functional>。
一個有用的函數對象的應用是accumulate() 算法。該函數計算容器中全部值的總和。記住這樣的值不必定是簡單的類型,經過重載operator+(),也能夠是類對象。
Listing 8. accum.cpp
#include <iostream.h> #include <numeric> // Need accumulate() #include <vector> // Need vector #include <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
『注意使用了函數對象的accumulate()的用法。accumulate() 在內部將每一個容器中的對象和第三個參數做爲multiplies函數對象的參數,multiplies(1,v)計算乘積。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究竟是怎麼實現的,最好的辦法是寫個簡單的程序,將程序中涉及到的模板源碼給copy下來,稍做整理,就能看懂了。因此沒有必要去買什麼《STL源碼剖析》之類的書籍,那些書可能反而浪費時間。』
有一類有用的函數對象是「發生器」(generator)。這類函數有本身的內存,也就是說它可以從先前的調用中記住一個值。例如隨機數發生器函數。
普通的C程序員使用靜態或全局變量 「記憶」上次調用的結果。但這樣作的缺點是該函數沒法和它的數據相分離『還有個缺點是要用TLS才能線程安全』。顯然,使用類來封裝一塊:「內存」更安全可靠。先看一下例子:
Listing 9. randfunc.cpp
#include <iostream.h> #include <stdlib.h> // Need random(), srandom() #include <time.h> // Need time() #include <algorithm> // Need random_shuffle() #include <vector> // Need vector #include <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; }
編譯運行結果以下:
$ 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
首先用下面的語句申明一個對象:
pointer_to_unary_function<unsigned int, unsigned int> ptr_RandInt = ptr_fun(RandInt);
這兒使用STL的單目函數模板定義了一個變量ptr_RandInt,並將地址初始化到咱們的函數RandInt()。單目函數接受一個參數,並返回一個值。如今random_shuffle()能夠以下調用:
random_shuffle(v.begin(), v.end(), ptr_RandInt);
在本例子中,發生器只是簡單的調用rand()函數。
關於常量引用的一點小麻煩(不翻譯了,VC下將例子中的const去掉)
下面的例子說明發生器函數類對象的使用。
Listing 10. fiborand.cpp
#include <iostream.h> #include <algorithm> // Need random_shuffle() #include <vector> // Need vector #include <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; }
編譯運行輸出以下:
$ 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 發生器封裝在一個類中,該類能從先前的「使用」中記憶運行結果。在本例中,類FiboRand 維護了一個數組和兩個索引變量I和j。
FiboRand類繼承自unary_function() 模板:
template <class Arg> class FiboRand : public unary_function<Arg, Arg> {...
Arg是用戶自定義數據類型。該類還定以了兩個成員函數,一個是構造函數,另外一個是operator()()函數,該操做符容許random_shuffle()算法象一個函數同樣「調用」一個FiboRand對象。
一個綁定器使用另外一個函數對象f()和參數值V建立一個函數對象。被綁定函數對象必須爲雙目函數,也就是說有兩個參數,A和B。STL 中的幫定器有:
舉例以下:
Listing 11. binder.cpp
#include <iostream.h> #include <algorithm> #include <functional> #include <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()計算知足特定條件的元素的數目。 這是經過將一個函數對象和一個參數捆綁到爲一個對象,並將該對象做爲算法的第三個參數實現的。 注意這個表達式:
bind1st(greater<int>(), 8)
該表達式將greater<int>()和一個參數值8捆綁爲一個函數對象。因爲使用了bind1st(),因此該函數至關於計算下述表達式:
8 > q
表達式中的q是容器中的對象。所以,完整的表達式
count_if(aList.begin(), aList.end(), bind1st(greater<int>(), 8), k);
計算全部小於或等於8的對象的數目。
所謂否認(negator)函數對象,就是它從另外一個函數對象建立而來,若是原先的函數返回真,則否認函數對象返回假。有兩個否認函數對象:not1()和not2()。not1()接受單目函數對象,not2()接受雙目函數對象。否認函數對象一般和幫定器一塊兒使用。例如,上節中用bind1nd來搜索q<=8的值:
count_if(aList.begin(), aList.end(), bind1st(greater<int>(), 8), k);
若是要搜索q>8的對象,則用bind2st。而如今能夠這樣寫:
start = find_if(aList.begin(), aList.end(), not1(bind1nd(greater<int>(), 6)));
你必須使用not1,由於bind1nd返回單目函數。
儘管不少程序員仍然在使用標準C函數,可是這就好像騎着毛驢尋找Mercedes同樣。你固然最終也會到達目標,可是你浪費了不少時間。
儘管有時候使用標準C函數確實方便(如使用sprintf()進行格式化輸出)。可是C函數不使用異常機制來報告錯誤,也不適合處理新的數據類型。並且標準C函數常用內存分配技術,沒有經驗的程序員很容易寫出bug來。.
C++標準庫則提供了更爲安全,更爲靈活的數據集處理方式。STL最初由HP實驗室的Alexander Stepanov和Meng Lee開發。最近,C++標準委員會採納了STL,儘管在不一樣的實現之間仍有細節差異。
STL的最主要的兩個特色:數據結構和算法的分離,非面向對象本質。訪問對象是經過象指針同樣的迭代器實現的;容器是象鏈表,矢量之類的數據結構,並按模板方式提供;算法是函數模板,用於操做容器中的數據。因爲STL以模板爲基礎,因此能用於任何數據類型和結構