Home » C++ algorithm random_shuffle() function

C++ algorithm random_shuffle() function

by Online Tutorials Library

C++ Algorithm random_shuffle()

C++ Algorithm random_shuffle() reorders the elements of a range by putting them at random places.

The first version uses an internal random number generator and the second version uses a random number generator which is a special kind of function object that is explicitly passed as an argument.

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.

result: An output iterator pointing the position of the first element in the destination range.

gen: A special function object called a 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.

The object in the range between result and the returned value are changed.

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 random_shuffle():

Output:

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

Example 2

Let’s see another simple example:

Output:

Here are the values in the vector:  1 2 3 4 5 6 7 8 9 10     Now we randomize the order of the values.    Here are the revised contents of the vector:  5 4 8 9 1 6 3 2 7 10    

Example 3

Let’s see another simple example:

Output:

Original order :  A   2   3   4   5   6   7   8   9  10   J   Q   K    Shuffling cards in uniformly random order ...   Pick any three cards ...   You have got   : 9, 8, 4  

Example 4

Let’s see another simple example:

Output:

myvector contains: 9 7 5 6 3 4 2 8 1  

Next TopicC++ Algorithm

You may also like