random_shuffle

Syntax:

    #include <algorithm>
    void random_shuffle( random_access_iterator start, random_access_iterator end );
    void random_shuffle( random_access_iterator start, random_access_iterator end, RandomNumberGenerator& rnd );

The random_shuffle() function randomly re-orders the elements in the range [start,end). If a random number generator function object rnd is supplied, it will be used instead of an internal random number generator.

The “internal” random number generator is not necessarily the one which can be accessed with rand() and seeded with srand(); this is implementation defined. The SGI STL implementation, for example, uses a different generator.

Example

// random_shuffle example
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
 
// random generator function:
ptrdiff_t myrandom (ptrdiff_t i) { return rand()%i;}
 
// pointer object to it:
ptrdiff_t (*p_myrandom)(ptrdiff_t) = myrandom;
 
int main () {
  srand ( unsigned ( time (NULL) ) );
  vector<int> myvector;
  vector<int>::iterator it;
 
  // 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:
  random_shuffle ( myvector.begin(), myvector.end() );
 
  // using myrandom:
  random_shuffle ( myvector.begin(), myvector.end(), p_myrandom);
 
  // print out content:
  cout << "myvector contains:";
  for (it=myvector.begin(); it!=myvector.end(); ++it)
    cout << " " << *it;
 
  cout << endl;
 
  return 0;
}

A possible output: myvector contains: 3 4 1 6 8 9 2 7 5

Related Topics: next_permutation, prev_permutation, random_sample, random_sample_n