STL algorithm算法shuffle , random_shuffle(46)

shuffle原型:

template 
  void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);
该函数是用来打乱范围内元素的顺序的。

其行为类似:

template 
  void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g)
{
  for (auto i=(last-first)-1; i>0; --i) {
    std::uniform_int_distribution d(0,i);
    swap (first[i], first[d(g)]);
  }
}
一个简单的例子:

// shuffle algorithm example
#include      // std::cout
#include     // std::shuffle
#include         // std::array
#include        // std::default_random_engine
#include        // std::chrono::system_clock

int main () {
  std::array foo {1,2,3,4,5,6,7,8,9};

  // obtain a time-based seed:
  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

  shuffle (foo.begin(), foo.end(), std::default_random_engine(seed));

  std::cout << "shuffled elements:";
  for (int& x: foo) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}
运行截图:

STL algorithm算法shuffle , random_shuffle(46)_第1张图片


random_shuffle原型:

std::random_shuffle

  • C++98
  • C++11
generator by default (1)
template 
  void random_shuffle (RandomAccessIterator first, RandomAccessIterator last);
specific generator (2)
template 
  void random_shuffle (RandomAccessIterator first, RandomAccessIterator last,
                       RandomNumberGenerator&& gen);

该函数也是用来打乱序列的顺序的。简单来说就是使序列里元素的位置变得随机。

行为类似于:

template 
  void random_shuffle (RandomAccessIterator first, RandomAccessIterator last,
                       RandomNumberGenerator& gen)
{
  iterator_traits::difference_type i, n;
  n = (last-first);
  for (i=n-1; i>0; --i) {
    swap (first[i],first[gen(i+1)]);
  }
}
一个简单的例子:

// random_shuffle example
#include      // std::cout
#include     // std::random_shuffle
#include        // std::vector
#include         // std::time
#include       // std::rand, std::srand

// random generator function:
int myrandom (int i) { return std::rand()%i;}

int main () {
  std::srand ( unsigned ( std::time(0) ) );
  std::vector myvector;

  // set some values:
  for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9

  // using built-in random generator:
  std::random_shuffle ( myvector.begin(), myvector.end() );

  // using myrandom:
  std::random_shuffle ( myvector.begin(), myvector.end(), myrandom);

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;

  std::cout << '\n';

  return 0;
}
运行截图:

STL algorithm算法shuffle , random_shuffle(46)_第2张图片




——————————————————————————————————————————————————————————————————

//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。

转载请注明出处:http://blog.csdn.net/qq844352155

author:天下无双

Email:[email protected]

2014-9-22

于GDUT

——————————————————————————————————————————————————————————————————





你可能感兴趣的:(STL,算法,STL,算法)