龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

STL组件之算法(1)(2)

时间:2011-04-12 23:18来源:未知 作者:admin 点击:
分享到:
(2)发生器函数类对象 下面的例子说明发生器函数类对象的使用。 Listing 10. fiborand.cpp #includeiostream.h #includealgorithm//Needrandom_shuffle() #includevector//Needvector

(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对象。


精彩图集

赞助商链接