STL组件之算法

开发 后端 算法
我们都知道STL的三大组件是迭代器,算法和容器。本文介绍STL组件中的一个算法,希望对你有帮助,一起来看。

STL提供了大量的模板类和函数,可以在OOP和常规编程中使用。所有的STL的大约50个算法都是完全通用的,而且不依赖于任何特定的数据类型。下面的小节说明了三个基本的STL组件:

1)迭代器提供了访问容器中对象的方法。例如,可以使用一对迭代器指定list或vector中的一定范围的对象。迭代器就如同一个指针。事实上,C++的指针也是一种迭代器。但是,迭代器也可以是那些定义了operator*()以及其他类似于指针的操作符地方法的类对象。

2)容器是一种数据结构,如list,vector,和deques ,以模板类的方法提供。为了访问容器中的数据,可以使用由容器类输出的迭代器。

3)算法是用来操作容器中的数据的模板函数。例如,STL用sort()来对一个vector中的数据进行排序,用find()来搜索一个list中的对象。函数本身与他们操作的数据的结构和类型无关,因此他们可以在从简单数组到高度复杂容器的任何数据结构上使用。

函数和函数对象

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

函数和断言

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

 

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

 

所谓断言函数,就是返回bool值的函数。

函数对象

除了给STL算法传递一个回调函数,你还可能需要传递一个类对象以便执行更复杂的操作。这样的一个对象就叫做函数对象。实际上函数对象就是一个类,但它和回调函数一样可以被回调。例如,在函数对象每次被for_each()或find_if()函数调用时可以保留统计信息。函数对象是通过重载 operator()()实现的。如果TanyClass定义了opeator()(),那么就可以这么使用:

 

  1. TAnyClass object; // Construct object  
  2. object(); // Calls TAnyClass::operator()() function  
  3. 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

 

  1. #include <iostream.h>  
  2. #include <numeric> // Need accumulate()  
  3. #include <vector> // Need vector  
  4. #include <functional> // Need multiplies() (or times())  
  5. #define MAX 10  
  6. vector<long> v(MAX); // Vector object  
  7. int main()  
  8. {  
  9. // Fill vector using conventional loop  
  10. //  
  11. for (int i = 0; i < MAX; i++)  
  12. v[i] = i + 1;  
  13. // Accumulate the sum of contained values  
  14. //  
  15. long sum =  
  16. accumulate(v.begin(), v.end(), 0);  
  17. cout << "Sum of values == " << sum << endl;  
  18. // Accumulate the product of contained values  
  19. //  
  20. long product =  
  21. accumulate(v.begin(), v.end(), 1, multiplies<long>());//注意这行  
  22. cout << "Product of values == " << product << endl;  
  23. return 0;  

编译输出如下:

 

  1. $ g++ accum.cpp  
  2. $ ./a.out  
  3. Sum of values == 55  
  4. Product of values == 3628800 

『注意使用了函数对象的accumulate()的用法。accumulate() 在内部将每个容器中的对象和第三个参数作为multiplies函数对象的参数,multiplies(1,v)计算乘积。VC中的这些模板的源代码如下:

 

  1. // TEMPLATE FUNCTION accumulate  
  2. template<class _II, class _Ty> inline 
  3. _Ty accumulate(_II _F, _II _L, _Ty _V)  
  4. {for (; _F != _L; ++_F)  
  5. _V = _V + *_F;  
  6. return (_V); }  
  7. // TEMPLATE FUNCTION accumulate WITH BINOP  
  8. template<class _II, class _Ty, class _Bop> inline 
  9. _Ty accumulate(_II _F, _II _L, _Ty _V, _Bop _B)  
  10. {for (; _F != _L; ++_F)  
  11. _V = _B(_V, *_F);  
  12. return (_V); }  
  13. // TEMPLATE STRUCT binary_function  
  14. template<class _A1, class _A2, class _R>  
  15. struct binary_function {  
  16. typedef _A1 first_argument_type;  
  17. typedef _A2 second_argument_type;  
  18. typedef _R result_type;  
  19. };  
  20. // TEMPLATE STRUCT multiplies  
  21. template<class _Ty>  
  22. struct multiplies : binary_function<_Ty, _Ty, _Ty> {  
  23. _Ty operator()(const _Ty& _X, const _Ty& _Y) const 
  24. {return (_X * _Y); }  
  25. }; 

 

引言:如果你想深入了解STL到底是怎么实现的,***的办法是写个简单的程序,将程序中涉及到的模板源码给copy下来,稍作整理,就能看懂了。所以没有必要去买什么《STL源码剖析》之类的书籍,那些书可能反而浪费时间。』

(1)发生器函数对象

有一类有用的函数对象是“发生器”(generator)。这类函数有自己的内存,也就是说它能够从先前的调用中记住一个值。例如随机数发生器函数。

普通的C程序员使用静态或全局变量 “记忆”上次调用的结果。但这样做的缺点是该函数无法和它的数据相分离『还有个缺点是要用TLS才能线程安全』。显然,使用类来封装一块:“内存”更安全可靠。先看一下例子:

Listing 9. randfunc.cpp

 

  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. using namespace std;  
  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. // Function prototypes  
  12. void Display(vector<int>& vr, const char *s);  
  13. unsigned int RandInt(const unsigned int n);  
  14. int main()  
  15. {  
  16. srandom( time(NULL) ); // Seed random generator  
  17. Display(v, "Before shuffle:");  
  18. pinter_to_unary_function<unsigned int, unsigned int>  
  19. ptr_RandInt = ptr_fun(RandInt); // Pointer to RandInt()//注意这行  
  20. random_shuffle(v.begin(), v.end(), ptr_RandInt);  
  21. Display(v, "After shuffle:");  
  22. return 0;  
  23. }  
  24. // Display contents of vector vr  
  25. void Display(vector<int>& vr, const char *s)  
  26. {  
  27. cout << endl << s << endl;  
  28. copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " "));  
  29. cout << endl;  
  30. }  
  31. // Return next random value in sequence modulo n  
  32. unsigned int RandInt(const unsigned int n)  
  33. {  
  34. return random() % n;  

编译运行结果如下:

 

  1. $ g++ randfunc.cpp  
  2. $ ./a.out  
  3. Before shuffle:  
  4. 1 2 3 4 5 6 7 8 9 10  
  5. After shuffle:  
  6. 6 7 2 8 3 5 10 1 9 4 

首先用下面的语句申明一个对象:

 

  1. pointer_to_unary_function<unsigned int, unsigned int>  
  2. ptr_RandInt = ptr_fun(RandInt); 

这儿使用STL的单目函数模板定义了一个变量ptr_RandInt,并将地址初始化到我们的函数RandInt()。单目函数接受一个参数,并返回一个值。现在random_shuffle()可以如下调用:

 

  1. random_shuffle(v.begin(), v.end(), ptr_RandInt); 

在本例子中,发生器只是简单的调用rand()函数。

关于常量引用的一点小麻烦(不翻译了,VC下将例子中的const去掉)

#p#

(2)发生器函数类对象

下面的例子说明发生器函数类对象的使用。

Listing 10. fiborand.cpp

 

  1. #include <iostream.h>  
  2. #include <algorithm> // Need random_shuffle()  
  3. #include <vector> // Need vector  
  4. #include <functional> // Need unary_function  
  5. using namespace std;  
  6. // Data to randomize  
  7. int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  
  8. vector<int> v(iarray, iarray + 10);  
  9. // Function prototype  
  10. void Display(vector<int>& vr, const char *s);  
  11. // The FiboRand template function-object class  
  12. template <class Arg>  
  13. class FiboRand : public unary_function<Arg, Arg> {  
  14. int i, j;  
  15. Arg sequence[18];  
  16. public:  
  17. FiboRand();  
  18. Arg operator()(const Arg& arg);  
  19. };  
  20. void main()  
  21. {  
  22. FiboRand<int> fibogen; // Construct generator object  
  23. cout << "Fibonacci random number generator" << endl;  
  24. cout << "using random_shuffle and a function object" << endl;  
  25. Display(v, "Before shuffle:");  
  26. random_shuffle(v.begin(), v.end(), fibogen);  
  27. Display(v, "After shuffle:");  
  28. }  
  29. // Display contents of vector vr  
  30. void Display(vector<int>& vr, const char *s)  
  31. {  
  32. cout << endl << s << endl;  
  33. copy(vr.begin(), vr.end(),  
  34. ostream_iterator<int>(cout, " "));  
  35. cout << endl;  
  36. }  
  37. // FiboRand class constructor  
  38. template<class Arg>  
  39. FiboRand<Arg>::FiboRand()  
  40. {  
  41. sequence[17] = 1;  
  42. sequence[16] = 2;  
  43. for (int n = 15; n > 0; n—)  
  44. sequence[n] = sequence[n + 1] + sequence[n + 2];  
  45. i = 17;  
  46. j = 5;  
  47. }  
  48. // FiboRand class function operator  
  49. template<class Arg>  
  50. Arg FiboRand<Arg>::operator()(const Arg& arg)  
  51. {  
  52. Arg k = sequence[i] + sequence[j];  
  53. sequence[i] = k;  
  54. i--;  
  55. j--;  
  56. if (i == 0) i = 17;  
  57. if (j == 0) j = 17;  
  58. return k % arg;  

编译运行输出如下:

 

  1. $ g++ fiborand.cpp  
  2. $ ./a.out  
  3. Fibonacci random number generator  
  4. using random_shuffle and a function object  
  5. Before shuffle:  
  6. 1 2 3 4 5 6 7 8 9 10  
  7. After shuffle:  
  8. 6 8 5 4 3 7 10 1 9 

该程序用完全不通的方法使用使用rand_shuffle。Fibonacci 发生器封装在一个类中,该类能从先前的“使用”中记忆运行结果。在本例中,类FiboRand 维护了一个数组和两个索引变量I和j。

FiboRand类继承自unary_function() 模板:

 

  1. template <class Arg>  
  2. class FiboRand : public unary_function<Arg, Arg> {... 

Arg是用户自定义数据类型。该类还定以了两个成员函数,一个是构造函数,另一个是operator()()函数,该操作符允许random_shuffle()算法象一个函数一样“调用”一个FiboRand对象。

#p#

(3)绑定器函数对象

一个绑定器使用另一个函数对象f()和参数值V创建一个函数对象。被绑定函数对象必须为双目函数,也就是说有两个参数,A和B。STL 中的帮定器有:

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

举例如下:

Listing 11. binder.cpp

 

  1. #include <iostream.h>  
  2. #include <algorithm>  
  3. #include <functional>  
  4. #include <list>  
  5. using namespace std;  
  6. // Data  
  7. int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  
  8. list<int> aList(iarray, iarray + 10);  
  9. int main()  
  10. {  
  11. int k = 0;  
  12. count_if(aList.begin(), aList.end(),  
  13. bind1st(greater<int>(), 8), k);  
  14. cout << "Number elements < 8 == " << k << endl;  
  15. return 0;  

Algorithm count_if()计算满足特定条件的元素的数目。 这是通过将一个函数对象和一个参数捆绑到为一个对象,并将该对象作为算法的第三个参数实现的。 注意这个表达式:

 

  1. bind1st(greater<int>(), 8) 

该表达式将greater<int>()和一个参数值8捆绑为一个函数对象。由于使用了bind1st(),所以该函数相当于计算下述表达式:

8 > q

表达式中的q是容器中的对象。因此,完整的表达式

 

  1. count_if(aList.begin(), aList.end(),  
  2. bind1st(greater<int>(), 8), k); 

计算所有小于或等于8的对象的数目。

(4)否定函数对象

所谓否定(negator)函数对象,就是它从另一个函数对象创建而来,如果原先的函数返回真,则否定函数对象返回假。有两个否定函数对象:not1()和 not2()。not1()接受单目函数对象,not2()接受双目函数对象。否定函数对象通常和帮定器一起使用。例如,上节中用bind1nd来搜索 q<=8的值:

 

  1. count_if(aList.begin(), aList.end(),  
  2. bind1st(greater<int>(), 8), k); 

如果要搜索q>8的对象,则用bind2st。而现在可以这样写:

 

  1. start = find_if(aList.begin(), aList.end(),  
  2. 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. 检测C++中的内存泄漏
  2. c/c++基础 预处理指令总结
  3. 详细介绍c++中的类对象内存模型
  4. C++基础 详细介绍const的用法
  5. C++初学者 const使用详解

 

责任编辑:于铁 来源: 互联网
相关推荐

2011-07-13 13:56:06

STL迭代器

2024-03-04 00:15:00

C++STL算法

2011-07-13 15:07:48

STLC++

2011-07-13 14:49:31

STLC++

2023-12-10 22:00:47

STLC++编程

2011-01-18 16:32:02

Ubuntu

2021-07-09 09:12:40

STL排序算法

2021-11-01 10:21:36

鸿蒙HarmonyOS应用

2011-07-13 14:58:53

STL容器

2021-10-14 15:14:36

鸿蒙HarmonyOS应用

2021-11-05 22:47:44

冒泡排序选择插入

2021-03-23 13:55:35

大数据算法

2011-05-07 16:07:32

复合机

2015-04-22 10:57:22

androidSwipeRefres

2021-02-22 21:49:33

Vue动态组件

2022-08-03 09:58:03

跨端框架实践

2021-09-05 07:35:58

lifecycleAndroid组件原理

2011-08-01 15:57:58

2016-12-09 09:23:50

android组件Service

2011-07-11 15:26:49

性能优化算法
点赞
收藏

51CTO技术栈公众号