This post will discuss how to shuffle a vector in C++.

1. Using std::random_shuffle function

The idea is to use the std::random_shuffle algorithm defined in the <algorithm> header. The C++ specification does not state the source of randomness for its built-in random generator and can be used with C++98/03 standard.

Download  Run Code

 
We can also add a custom random number generator as an additional argument to the std::random_shuffle function, as shown below:

Download  Run Code

2. Using std::shuffle function

From C++11 onward, we should prefer std::shuffle over std::random_shuffle. It randomly rearranges the elements in the specified range using the specified uniform random number generator. We can use any of the standard generators defined in the <random> header introduced with C++11.

Download  Run Code

 
The std::default_random_engine generator produces the same output every time. To get a different output, the idea is to use a custom random number generator that can be seeded from an external source.

Download  Run Code

3. Using Fisher-Yates Shuffle Algorithm

Another good alternative is to use Fisher–Yates shuffle to generate random permutations. The algorithm does a linear scan of the vector and swaps each element with a random element among all remaining elements, including the element itself.

Download  Run Code

That’s all about shuffling a vector in C++.