random_shuffle

Random_shuffle:随机打乱容器.
	// TEMPLATE FUNCTION random_shuffle
template<class _RanIt,
	class _Diff> inline
	void _Random_shuffle(_RanIt _First, _RanIt _Last, _Diff *)
	{	// shuffle [_First, _Last)
	const int _RANDOM_BITS = 15;	// minimum random bits from rand()
	const int _RANDOM_MAX = (1U << _RANDOM_BITS) - 1;

	_RanIt _Next = _First;
	for (unsigned long _Index = 2; ++_Next != _Last; ++_Index)
		{	// assume unsigned long big enough for _Diff count
		unsigned long _Rm = _RANDOM_MAX;
		unsigned long _Rn = _CSTD rand() & _RANDOM_MAX;
		for (; _Rm < _Index && _Rm != ~0UL;
			_Rm = _Rm << _RANDOM_BITS | _RANDOM_MAX)
			_Rn = _Rn << _RANDOM_BITS
				| (_CSTD rand() & _RANDOM_MAX);	// build random value

		_STD iter_swap(_Next, _First + _Diff(_Rn % _Index));	// swap a pair
		}
	}
函数产生一个随机容器.
// TEMPLATE FUNCTION random_shuffle WITH RANDOM FN
template<class _RanIt,
	class _Fn1,
	class _Diff> inline
	void _Random_shuffle(_RanIt _First, _RanIt _Last, _Fn1& _Func, _Diff *)
	{	// shuffle nonempty [_First, _Last) using random function _Func
	_RanIt _Next = _First;
	for (_Diff _Index = 2; ++_Next != _Last; ++_Index)
		_STD iter_swap(_Next, _First + _Diff(_Func(_Index) % _Index));
	}
这个函数就比较容易理解.
举例:
class MyRadom{
public:
	ptrdiff_t operator()( ptrdiff_t max )
	{
		double temp;
		temp = static_cast<double>( rand() )
			/ static_cast<double>(RAND_MAX);
		return static_cast<ptrdiff_t>(temp*max );
	}
};
int main()
{
	vector<int> vecInt;
	for ( int i = 0;i <= 9;++ i )
	{
		vecInt.push_back( i );
	}
	random_shuffle( vecInt.begin(),vecInt.end() );
	random_shuffle( vecInt.begin(),vecInt.end(),MyRadom() );
	copy( vecInt.begin(),vecInt.end(),ostream_iterator<int>( cout," " ) );
	system( "pause" );
	return 0;
}



 

你可能感兴趣的:(function,System,Random,Class,Build,pair)