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.
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.The random_shuffle()
function does not return any value.
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;}
random_shuffle()
function and pass the required parameters.In this way, we can use the random_shuffle()
function to randomly shuffle elements in C++.