zoukankan      html  css  js  c++  java
  • STL 源代码剖析 算法 stl_algo.h -- random_shuffle

    本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


    random_shuffle

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------


    描写叙述:将[first,last)的元素次序随机重排。
    思路:
    必须是 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, " "));
    }


  • 相关阅读:
    pop动画
    CoreData的用法
    高德地图详细使用方法
    GDataXML配置过程
    图片懒加载(仿SDWebImage)
    GCD创建单例
    多线程-多线程基础
    Zookeeper-集群与单机实践
    oracle-union all与order by联合使用
    分布式和集中式架构
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5217449.html
Copyright © 2011-2022 走看看