首页 > 代码库 > STL 源码剖析 算法 stl_algo.h -- random_shuffle
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, " ")); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。