C++ Algorithm shuffle()
C++ Algorithm shuffle() function reorders the elements of a range by putting them at random places, using g as uniform random number generator.
Syntax
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
None
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():
Output:
shuffled elements: 4 1 3 5 2
Example 2
Let’s see another simple example:
Output:
8 6 10 4 2 3 7 1 9 5
Example 3
Let’s see another simple example:
Output:
before: 0 1 2 3 4 5 6 7 8 9 after: 4 3 1 2 7 0 8 9 6 5