blob: f7e03f502449937b99e0e4532c69436ab5fc1e5b [file] [log] [blame]
 random_shuffle()
Apache C++ Standard Library Reference Guide

random_shuffle()

Library:  Algorithms

Function

Local Index

No Entries

Summary

Algorithm that randomly shuffles elements of a collection

Synopsis

#include <algorithm>

namespace std {
template <class RandomAccessIterator>
void random_shuffle(RandomAccessIterator start,
RandomAccessIterator finish);

template <class RandomAccessIterator,
class RandomNumberGenerator>
void random_shuffle(RandomAccessIterator start,
RandomAccessIterator finish,
RandomNumberGenerator& rand);
}

Description

The random_shuffle() algorithm shuffles the elements in the range [start, finish) with uniform distribution. random_shuffle() can take a particular random number generating function object rand (where rand takes a positive argument n of type convertible from std::iterator_traits<RandomAccessIterator>::difference_type) and returns a randomly chosen value between 0 and n - 1.

Complexity

In the random_shuffle() algorithm, (finish - start) - 1 swaps are done.

Example

//
//  rndshufl.cpp
//

#include <algorithm>   // for random_shuffle
#include <iostream>    // for cout, endl
#include <iterator>    // for ostream_iterator
#include <string>      // for string

int main ()
{
// Create a string of doubles (unusual? maybe,
// but why not...)
typedef std::basic_string<double,
std::char_traits<double>,
std::allocator<double> >
Bizarre;

// Initialize a Bizarre with an array of values.
const Bizarre::value_type a[] = { 1, 2, 3, 4, 5,
6, 7, 8, 9, 10 };

Bizarre b (a + 0, a + sizeof a / sizeof *a);

typedef std::ostream_iterator<double, char,
std::char_traits<char> >
Iter;

// Suppress decimal point in output.
std::cout.precision (0);

// Print out elements in original (sorted) order.
std::cout << "Elements before random_shuffle: \n     ";
std::copy (b.begin (), b.end (), Iter (std::cout," "));

// Mix them up with random_shuffle.
std::random_shuffle (b.begin (), b.end ());

// Print out the mixed up elements.
std::cout << "\n\nElements after random_shuffle: \n     ";
std::copy (b.begin (), b.end (), Iter (std::cout, " "));
std::cout << std::endl;

return 0;
}

Program Output:

Elements before random_shuffle:
1 2 3 4 5 6 7 8 9 10

Elements after random_shuffle:
9 8 7 6 2 3 1 4 5 10

Standards Conformance

ISO/IEC 14882:1998 -- International Standard for Information Systems --Programming Language C++, Section 25.2.11