#include <algorithm> #include <vector> #include <iostream> //using namespace std; using std::copy; using std::cout; template<class _Ty> inline void swap(_Ty& _Left, _Ty& _Right) { // exchange values stored at _Left and _Right if (&_Left != &_Right) { // different, worth swapping _Ty _Tmp = _Left; _Left = _Right; _Right = _Tmp; } } template<class _FwdIt1, class _FwdIt2> inline void iter_swap(_FwdIt1 _Left, _FwdIt2 _Right) { // swap *_Left and *_Right std::swap(*_Left, *_Right); } /************************************************************************/ /* */ /************************************************************************/ template<class _RanIt, class _Diff> inline void my_Random_shuffle(_RanIt _First, _RanIt _Last, _Diff *) { // shuffle [_First, _Last) _DEBUG_RANGE(_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 = ::rand() & _RANDOM_MAX; for (; _Rm < _Index && _Rm != ~0UL; _Rm = _Rm << _RANDOM_BITS | _RANDOM_MAX ) _Rn = _Rn << _RANDOM_BITS | (::rand() & _RANDOM_MAX); // build random value std::iter_swap(_Next, _First + _Diff(_Rn % _Index)); // swap a pair } } template<class _RanIt> inline void my_random_shuffle(_RanIt _First, _RanIt _Last) { // shuffle [_First, _Last) if (_First != _Last) my_Random_shuffle(_CHECKED_BASE(_First), _CHECKED_BASE(_Last), _Dist_type(_First)); } int main() { std::vector<int, std::allocator<int>> vec; for (int ix = 0;ix < 20; ix++) { vec.push_back( ix ); } my_random_shuffle(vec.begin(),vec.end()); cout << "random_shuffle of sequence of value 1...20:/n"; copy(vec.begin(), vec.end(), std::ostream_iterator<int>(cout, " ")); return 0; }