Brings the elements into a random order

You're viewing an older version of this page (#4155). View the current version.

View versions (1)

Definition

The random_shuffle() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class RandomAccessIterator >
   void random_shuffle(
      RandomAccessIterator first, 
      RandomAccessIterator last
   );
template < class RandomAccessIterator, class RandomNumberGenerator >
   void random_shuffle(
      RandomAccessIterator first, 
      RandomAccessIterator last, 
      RandomNumberGenerator& rand
   );

Parameters:

ParameterDescription
firstA random-access iterator addressing the position of the first element in the range to be rearranged
lastA random-access iterator addressing the position one past the final element in the range to be rearranged
randA special function object called a random number generator

Description

Random_shuffle function reorders the elements of a range by putting them at random places.

The first version uses an internal random number generator, and the second uses a Random Number Generator, a special kind of function object, that is explicitly passed as an argument.

Return Value

None.

Complexity

The complexity is linear; performs as many calls to swap as the length of the range [first,last) - 1.

References

Example 1
Problem

This program illustrates the use of the STL random_shuffle() algorithm (default version) to randomize the order of values in a vector of integers.

Workings
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
  int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  vector<int> v(a, a+10);

  cout <<"\nHere are the values in the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  cout << "\nNow we randomize the order of the values.";
  random_shuffle(v.begin(), v.end());

  cout <<"\nHere are the revised contents of the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  return 0;
}
Solution

Output:

Here are the values in the vector:
1 2 3 4 5 6 7 8 9 10

Now we randomize the order of the values.

Here are the revised contents of the vector:
9 2 10 3 1 6 8 4 5 7

See Also