STL 快速入门(二)

本章全文内容较长。


使用迭代器编程

你已经见到了迭代器的一些例子,现在我们将关注每种特定的迭代器如何使用。由于使用迭代器需要关于STL容器类和算法的知识,在阅读了后面的两章后你可能需要重新复习一下本章内容。

输入迭代器

输入迭代器是最普通的类型。输入迭代器至少能够使用==和!=测试是否相等;使用*来访问数据;使用++操作来递推迭代器到下一个元素或到达past-the-end 值。

为了理解迭代器和STL函数是如何使用它们的,现在来看一下find()模板函数的定义:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. template <class InputIterator, class T>  
  2. InputIterator find(  
  3.   InputIterator first, InputIterator last, const T& value) {  
  4.     while (first != last && *first != value) ++first;  
  5.     return first;  
  6.   }  

注意

在find()算法中,注意如果first和last指向不同的容器,该算法可能陷入死循环。

输出迭代器

输出迭代器缺省只写,通常用于将数据从一个位置拷贝到另一个位置。由于输出迭代器无法读取对象,因此你不会在任何搜索和其他算法中使用它。要想读取一个拷贝的值,必须使用另一个输入迭代器(或它的继承迭代器)。

Listing 3. outiter.cpp

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <iostream.h>  
  2. #include <algorithm>   // Need copy()  
  3. #include <vector>      // Need vector  
  4.    
  5. using namespace std;  
  6.    
  7. double darray[10] =  
  8.   {1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9};  
  9.    
  10. vector<double> vdouble(10);  
  11.    
  12. int main()  
  13. {  
  14.   vector<double>::iterator outputIterator = vdouble.begin();  
  15.   copy(darray, darray + 10, outputIterator);  
  16.   while (outputIterator != vdouble.end()) {  
  17.     cout << *outputIterator << endl;  
  18.     outputIterator++;  
  19.   }  
  20.   return 0;  
  21. }  

注意

当使用copy()算法的时候,你必须确保目标容器有足够大的空间,或者容器本身是自动扩展的。

前推迭代器

前推迭代器能够读写数据值,并能够向前推进到下一个值。但是没法递减。replace()算法显示了前推迭代器的使用方法。

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. template <class ForwardIterator, class T>  
  2. void replace (ForwardIterator first,  
  3.               ForwardIterator last,  
  4.               const T& old_value,  
  5.               const T& new_value);  
  6. 使用replace()将[first,last]范围内的所有值为old_value的对象替换为new_value。:  
  7. 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

 
 
  1. #include <iostream.h>  
  2. #include <stdlib.h>    // Need random(), srandom()  
  3. #include <time.h>      // Need time()  
  4. #include <algorithm>   // Need sort(), copy()  
  5. #include <vector>      // Need vector  
  6.    
  7. using namespace std;  
  8.    
  9. void Display(vector<int>& v, const char* s);  
  10.    
  11. int main()  
  12. {  
  13.   // Seed the random number generator  
  14.   srandom( time(NULL) );  
  15.    
  16.   // Construct vector and fill with random integer values  
  17.   vector<int> collection(10);  
  18.   for (int i = 0; i < 10; i++)  
  19.     collection[i] = random() % 10000;;  
  20.    
  21.   // Display, sort, and redisplay  
  22.   Display(collection, "Before sorting");  
  23.   sort(collection.begin(), collection.end());  
  24.   Display(collection, "After sorting");  
  25.   return 0;  
  26. }  
  27.    
  28. // Display label s and contents of integer vector v  
  29. void Display(vector<int>& v, const char* s)  
  30. {  
  31.   cout << endl << s << endl;  
  32.   copy(v.begin(), v.end(),  
  33.     ostream_iterator<int>(cout, "\t"));  
  34.   cout << endl;  
  35. }  

函数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));

三种插入迭代器如下:

·        普通插入器 将对象插入到容器任何对象的前面。

·        Front inserters 将对象插入到数据集的前面——例如,链表表头。

·        Back inserters 将对象插入到集合的尾部——例如,矢量的尾部,导致矢量容器扩展。

使用插入迭代器可能导致容器中的其他对象移动位置,因而使得现存的迭代器非法。例如,将一个对象插入到矢量容器将导致其他值移动位置以腾出空间。一般来说,插入到象链表这样的结构中更为有效,因为它们不会导致其他对象移动。

Listing 5. insert.cpp

 
 
  1. #include <iostream.h>  
  2. #include <algorithm>  
  3. #include <list>  
  4.    
  5. using namespace std;  
  6.    
  7. int iArray[5] = { 1, 2, 3, 4, 5 };  
  8.    
  9. void Display(list<int>& v, const char* s);  
  10.    
  11. int main()  
  12. {  
  13.   list<int> iList;  
  14.    
  15.   // Copy iArray backwards into iList  
  16.   copy(iArray, iArray + 5, front_inserter(iList));  
  17.   Display(iList, "Before find and copy");  
  18.    
  19.   // Locate value 3 in iList  
  20.   list<int>::iterator p =  
  21.     find(iList.begin(), iList.end(), 3);  
  22.    
  23.   // Copy first two iArray values to iList ahead of p  
  24.   copy(iArray, iArray + 2, inserter(iList, p));  
  25.   Display(iList, "After find and copy");  
  26.    
  27.   return 0;  
  28. }  
  29.    
  30. void Display(list<int>& a, const char* s)  
  31. {  
  32.   cout << s << endl;  
  33.   copy(a.begin(), a.end(),  
  34.     ostream_iterator<int>(cout, " "));  
  35.   cout << endl;  
  36. }  

运行结果如下:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. $ g++ insert.cpp  
  2. $ ./a.out  
  3. Before find and copy  
  4. 5 4 3 2 1  
  5. After find and copy  
  6. 5 4 1 2 3 2 1  

可以将front_inserter替换为back_inserter试试。

如果用find()去查找在列表中不存在的值,例如99。由于这时将p设置为past-the-end 值。最后的copy()函数将iArray的值附加到链表的后部。

混合迭代器函数

在涉及到容器和算法的操作中,还有两个迭代器函数非常有用:

·        advance() 按指定的数目增减迭代器。

·        distance() 返回到达一个迭代器所需(递增)操作的数目。

例如:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. list<int> iList;  
  2. list<int>::iterator p =  
  3.   find(iList.begin(), iList.end(), 2);  
  4. cout << "before: p == " << *p << endl;  
  5. advance(p, 2);  // same as p = p + 2;  
  6. cout << "after : p == " << *p << endl;  
  7.    
  8. int k = 0;  
  9. distance(p, iList.end(), k);  
  10. cout << "k == " << k << endl;  
  11.    

advance()函数接受两个参数。第二个参数是向前推进的数目。对于前推迭代器,该值必须为正,而对于双向迭代器和随机访问迭代器,该值可以为负。

使用 distance()函数来返回到达另一个迭代器所需要的步骤。

注意

distance()函数是迭代的,也就是说,它递增第三个参数。因此,你必须初始化该参数。未初始化该参数几乎注定要失败。

函数和函数对象

STL中,函数被称为算法,也就是说它们和标准C库函数相比,它们更为通用。STL算法通过重载operator()函数实现为模板类或模板函数。这些类用于创建函数对象,对容器中的数据进行各种各样的操作。下面的几节解释如何使用函数和函数对象。

函数和断言

经常需要对容器中的数据进行用户自定义的操作。例如,你可能希望遍历一个容器中所有对象的STL算法能够回调自己的函数。例如

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <iostream.h>  
  2. #include <stdlib.h>     // Need random(), srandom()  
  3. #include <time.h>       // Need time()  
  4. #include <vector>       // Need vector  
  5. #include <algorithm>    // Need for_each()  
  6.    
  7. #define VSIZE 24        // Size of vector  
  8. vector<long> v(VSIZE);  // Vector object  
  9.    
  10. // Function prototypes  
  11. void initialize(long &ri);  
  12. void show(const long &ri);  
  13. bool isMinus(const long &ri);  // Predicate function  
  14.    
  15. int main()  
  16. {  
  17.   srandom( time(NULL) );  // Seed random generator  
  18.    
  19.   for_each(v.begin(), v.end(), initialize);//调用普通函数  
  20.   cout << "Vector of signed long integers" << endl;  
  21.   for_each(v.begin(), v.end(), show);  
  22.   cout << endl;  
  23.    
  24.   // Use predicate function to count negative values  
  25.   //  
  26.   int count = 0;  
  27.   vector<long>::iterator p;  
  28.   p = find_if(v.begin(), v.end(), isMinus);//调用断言函数  
  29.   while (p != v.end()) {  
  30.     count++;  
  31.     p = find_if(p + 1, v.end(), isMinus);  
  32.   }  
  33.   cout << "Number of values: " << VSIZE << endl;  
  34.   cout << "Negative values : " << count << endl;  
  35.    
  36.   return 0;  
  37. }  
  38.    
  39. // Set ri to a signed integer value  
  40. void initialize(long &ri)  
  41. {  
  42.   ri = ( random() - (RAND_MAX / 2) );  
  43.   //  ri = random();  
  44. }  
  45.    
  46. // Display value of ri  
  47. void show(const long &ri)  
  48. {  
  49.   cout << ri << "  ";  
  50. }  
  51.    
  52. // Returns true if ri is less than 0  
  53. bool isMinus(const long &ri)  
  54. {  
  55.   return (ri < 0);  
  56. }  
  57.    


所谓断言函数,就是返回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  

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <iostream.h>  
  2. #include <numeric>      // Need accumulate()  
  3. #include <vector>       // Need vector  
  4. #include <functional>   // Need multiplies() (or times())  
  5.    
  6. #define MAX 10  
  7. vector<long> v(MAX);    // Vector object  
  8.    
  9. int main()  
  10. {  
  11.   // Fill vector using conventional loop  
  12.   //  
  13.   for (int i = 0; i < MAX; i++)  
  14.     v[i] = i + 1;  
  15.    
  16.   // Accumulate the sum of contained values  
  17.   //  
  18.   long sum =  
  19.     accumulate(v.begin(), v.end(), 0);  
  20.   cout << "Sum of values == " << sum << endl;  
  21.    
  22.   // Accumulate the product of contained values  
  23.   //  
  24.   long product =  
  25.     accumulate(v.begin(), v.end(), 1, multiplies<long>());//注意这行  
  26.   cout << "Product of values == " << product << endl;  
  27.    
  28.   return 0;  
  29. }  

编译输出如下:

$ 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

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <iostream.h>  
  2. #include <stdlib.h>    // Need random(), srandom()  
  3. #include <time.h>      // Need time()  
  4. #include <algorithm>   // Need random_shuffle()  
  5. #include <vector>      // Need vector  
  6. #include <functional>  // Need ptr_fun()  
  7.    
  8. using namespace std;  
  9.    
  10. // Data to randomize  
  11. int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  
  12. vector<int> v(iarray, iarray + 10);  
  13.    
  14. // Function prototypes  
  15. void Display(vector<int>& vr, const char *s);  
  16. unsigned int RandInt(const unsigned int n);  
  17.    
  18. int main()  
  19. {  
  20.   srandom( time(NULL) );  // Seed random generator  
  21.   Display(v, "Before shuffle:");  
  22.    
  23.   pointer_to_unary_function<unsigned int, unsigned int>  
  24.     ptr_RandInt = ptr_fun(RandInt);  // Pointer to RandInt()//注意这行  
  25.   random_shuffle(v.begin(), v.end(), ptr_RandInt);  
  26.    
  27.   Display(v, "After shuffle:");  
  28.   return 0;  
  29. }  
  30.    
  31. // Display contents of vector vr  
  32. void Display(vector<int>& vr, const char *s)  
  33. {  
  34.   cout << endl << s << endl;  
  35.   copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " "));  
  36.   cout << endl;  
  37. }  
  38.    
  39.    
  40. // Return next random value in sequence modulo n  
  41. unsigned int RandInt(const unsigned int n)  
  42. {  
  43.   return random() % n;  
  44. }  
  45. 编译运行结果如下:  
  46. $ g++ randfunc.cpp  
  47. $ ./a.out  
  48. Before shuffle:  
  49. 1 2 3 4 5 6 7 8 9 10  
  50. After shuffle:  
  51. 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

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <iostream.h>  
  2. #include <algorithm>   // Need random_shuffle()  
  3. #include <vector>      // Need vector  
  4. #include <functional>  // Need unary_function  
  5.    
  6. using namespace std;  
  7.    
  8. // Data to randomize  
  9. int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  
  10. vector<int> v(iarray, iarray + 10);  
  11.    
  12. // Function prototype  
  13. void Display(vector<int>& vr, const char *s);  
  14.    
  15. // The FiboRand template function-object class  
  16. template <class Arg>  
  17. class FiboRand : public unary_function<Arg, Arg> {  
  18.   int i, j;  
  19.   Arg sequence[18];  
  20. public:  
  21.   FiboRand();  
  22.   Arg operator()(const Arg& arg);  
  23. };  
  24.    
  25. void main()  
  26. {  
  27.   FiboRand<int> fibogen;  // Construct generator object  
  28.   cout << "Fibonacci random number generator" << endl;  
  29.   cout << "using random_shuffle and a function object" << endl;  
  30.   Display(v, "Before shuffle:");  
  31.   random_shuffle(v.begin(), v.end(), fibogen);  
  32.   Display(v, "After shuffle:");  
  33. }  
  34.    
  35. // Display contents of vector vr  
  36. void Display(vector<int>& vr, const char *s)  
  37. {  
  38.   cout << endl << s << endl;  
  39.   copy(vr.begin(), vr.end(),  
  40.     ostream_iterator<int>(cout, " "));  
  41.   cout << endl;  
  42. }  
  43.    
  44. // FiboRand class constructor  
  45. template<class Arg>  
  46. FiboRand<Arg>::FiboRand()  
  47. {  
  48.   sequence[17] = 1;  
  49.   sequence[16] = 2;  
  50.   for (int n = 15; n > 0; n—)  
  51.     sequence[n] = sequence[n + 1] + sequence[n + 2];  
  52.   i = 17;  
  53.   j = 5;  
  54. }  
  55.    
  56. // FiboRand class function operator  
  57. template<class Arg>  
  58. Arg FiboRand<Arg>::operator()(const Arg& arg)  
  59. {  
  60.   Arg k = sequence[i] + sequence[j];  
  61.   sequence[i] = k;  
  62.   i--;  
  63.   j--;  
  64.   if (i == 0) i = 17;  
  65.   if (j == 0) j = 17;  
  66.   return k % arg;  
  67. }  
  68. 编译运行输出如下:  
  69. $ g++ fiborand.cpp  
  70. $ ./a.out  
  71. Fibonacci random number generator  
  72. using random_shuffle and a function object  
  73. Before shuffle:  
  74. 1 2 3 4 5 6 7 8 9 10  
  75. After shuffle:  
  76. 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 中的帮定器有:

·        bind1st() 创建一个函数对象,该函数对象将值V作为第一个参数A。

·        bind2nd()创建一个函数对象,该函数对象将值V作为第二个参数B。

举例如下:

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返回单目函数。


总结:使用标准模板库 (STL)

尽管很多程序员仍然在使用标准C函数,但是这就好像骑着毛驴寻找Mercedes一样。你当然最终也会到达目标,但是你浪费了很多时间。

尽管有时候使用标准C函数确实方便(如使用sprintf()进行格式化输出)。但是C函数不使用异常机制来报告错误,也不适合处理新的数据类型。而且标准C函数经常使用内存分配技术,没有经验的程序员很容易写出bug来。.

C++标准库则提供了更为安全,更为灵活的数据集处理方式。STL最初由HP实验室的Alexander Stepanov和Meng Lee开发。最近,C++标准委员会采纳了STL,尽管在不同的实现之间仍有细节差别。

STL的最主要的两个特点:数据结构和算法的分离,非面向对象本质。访问对象是通过象指针一样的迭代器实现的;容器是象链表,矢量之类的数据结构,并按模板方式提供;算法是函数模板,用于操作容器中的数据。由于STL以模板为基础,所以能用于任何数据类型和结构。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值