How to use the random_shuffle() function in C++

The random_shuffle() function in C++ is used to randomly shuffle elements within a specified range.

This function is available in the <algorithm.h> header file.

Parameters

The random_shuffle() function accepts the following parameters:

  • first: an iterator that points to the first index of the array or vector from which we want to randomly shuffle the elements.
  • last: an iterator that points to the last index of the array or vector until which we want to rotate the elements.
  • gen: an optional parameter that specifies a unary function, which tells how to shuffle the elements.

Return value

The random_shuffle() function does not return any value.

Code

Let’s look at the code to understand it better.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec = {1,2,3,4,5,6,7,8,9};
random_shuffle(vec.begin(), vec.end());
cout << "Updated vector: ";
for (int x: vec)
cout << x << " ";
return 0;
}

Explanation

  • From lines 1 to 3, we import the required libraries.
  • In line 7, we create a vector containing integer values.
  • In line 9, we call the random_shuffle() function and pass the required parameters.
  • Finally, from lines 11 to 13, we print the randomly shuffled vector.

In this way, we can use the random_shuffle() function to randomly shuffle elements in C++.

Free Resources