$ 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 = {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