STL 源代码剖析 算法 stl_algo.h -- random_shuffle
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
random_shuffle
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
思路:
必须是 RandomAccessIterator
1.遍历区间
2.产生[0,i)中的一个随机数rand。将*(first+rand)与i交换
??怎么证明随机性
源代码:
template <class RandomAccessIterator> inline void random_shuffle(RandomAccessIterator first, RandomAccessIterator last) { __random_shuffle(first, last, distance_type(first)); } template <class RandomAccessIterator, class RandomNumberGenerator> void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& rand) { //这里必须是传引用。由于随机数产生器有局部状态。每次被调用都会改变 if (first == last) return; for (RandomAccessIterator i = first + 1; i != last; ++i) iter_swap(i, first + rand((i - first) + 1)); } template <class RandomAccessIterator, class Distance> void __random_shuffle(RandomAccessIterator first, RandomAccessIterator last, Distance*) { if (first == last) return; for (RandomAccessIterator i = first + 1; i != last; ++i) #ifdef __STL_NO_DRAND48 iter_swap(i, first + Distance(rand() % ((i - first) + 1))); #else iter_swap(i, first + Distance(lrand48() % ((i - first) + 1))); #endif }
演示样例:
int main() { vector<int> vec; for(int ix = 0; ix < 10; ix++) vec.push_back(ix); random_shuffle(vec.begin(), vec.end()); copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " ")); }