STL示例07(random_shuffle第三个参数调用方法)

//STL示例 利用模版类做参数使random_shuffle获得随机数
#include <iostream>
#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; 
	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);//使用模版类函数fibogen做随机数发生器
	Display(v, "After shuffle:");
}

void Display(vector<int>& vr, const char *s)
{
	cout << endl << s << endl;
	copy(vr.begin(), vr.end(),ostream_iterator<int>(cout, " "));//显示容器内所有元素
	cout << endl;
}

//模版类函数FiboRand的构造函数.利用菲波拉契数列初始化sequence各个元素
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;
}

/*random_shuffle三个参数的原型
template<class _RI, class _Pf> inline
void random_shuffle(_RI _F, _RI _L, _Pf& _R)
{if (_F != _L)
_Random_shuffle(_F, _L, _R, _Dist_type(_F)); }
其中_Random_shuffle调用如下
template<class _RI, class _Pf, class _Pd> inline
void _Random_shuffle(_RI _F, _RI _L, _Pf& _R, _Pd *)
{_RI _X = _F;
for (_Pd _D = 1; ++_X != _L; ++_D)
iter_swap(_X, _F + _Pd(_R(_D))); }
*/
template<class Arg>
Arg FiboRand<Arg>::operator()(const Arg& arg)//利用operator重载()操作符
{
	//根据原型更好的理解函数random_shuffle的操作,
	//在_R(_D)这里重载操作符(),_D开始为1直到10的时候不满足条件退出循环
	cout<<"arg="<<arg<<endl;
	Arg k = sequence[i] + sequence[j];
	sequence[i] = k;
	i--;
	j--;
	if (i == 0) i = 17;
	if (j == 0) j = 17;
	return k % arg;
}

你可能感兴趣的:(STL示例07(random_shuffle第三个参数调用方法))