STL组件之算法(1)(2)
(2)发生器函数类对象
下面的例子说明发生器函数类对象的使用。
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对象。
- 上一篇:STL组件之迭代器(1)
- 下一篇:STL容器之向量vector容器