Algorithm Shuffle Function

C++ Algorithm shuffle function reorders the elements of a range by putting them at random places, using g as uniform random number generator.

Syntax

Example

template <class RandomAccessIterator, class URNG>
  void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);

Parameter

first : A random access iterator pointing the position of the first element in the range to be rearranged.

last : A random access iterator pointing the position one past the final element in the range to be rearranged.

g : A special function object called a uniform random number generator.

Return value

Complexity

Complexity is linear in the range [first, last) : obtain random values and swaps elements.

Data races

The object in the range [first, last) are modified.

Exceptions

This function throws an exception if any of random number generations, the element swaps or an operation on iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of shuffle:

Example

#include <iostream>     // std::cout
#include <algorithm>    // std::shuffle
#include <array>        // std::array
#include <random>       // std::default_random_engine
#include <chrono>       // std::chrono::system_clock

using namespace std;

int main () {
  array<int,5> foo {1,2,3,4,5};

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

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

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

  return 0;
}

Output:

Output

shuffled elements: 4 1 3 5 2

Example 2

Let's see another simple example:

Example

#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>

using namespace std;
 
int main()
{
    vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
    random_device rd;
    mt19937 g(rd());
 
    shuffle(v.begin(), v.end(), g);
 
    copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
    cout << "\n";
    
    return 0;
}

Output:

Output

8 6 10 4 2 3 7 1 9 5

Example 3

Let's see another simple example:

Example

#include <algorithm>
#include <iostream>
#include <vector>
#include <numeric>
#include <iterator>
#include <random>

using namespace std;

int main() {
  vector<int> v(10);
  iota(v.begin(), v.end(), 0);

  cout << "before: ";
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
  cout << endl;

  random_device seed_gen;
  mt19937 engine(seed_gen());
  shuffle(v.begin(), v.end(), engine);

  cout << " after: ";
  copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
  cout << endl;
  
  return 0;
}

Output:

Output

before: 0 1 2 3 4 5 6 7 8 9 
 after: 4 3 1 2 7 0 8 9 6 5

Input Required

This code uses input(). Please provide values below: