7.3. Randomly Shuffling Data
Problem
You have a sequence of data, and you need to jumble it into some random order.
Solution
Use the random_shuffle standard algorithm, defined
in <algorithm>. random_shuffle takes two random-access iterators, and (optionally) a random-number generation functor, and
rearranges the elements in the range at random. Example 7-3 shows how to do this.
Example 7-3. Shuffling a sequence at random
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include "utils.h" // For printContainer(): see 7.10
using namespace std;
int main() {
vector<int> v;
back_insert_iterator<std::vector<int> > p =
back_inserter(v);
for (int i = 0; i < 10; ++i)
*p = i;
printContainer(v, true);
random_shuffle(v.begin(), v.end());
printContainer(v, true);
}Your output might look like this:
----- 0 1 2 3 4 5 6 7 8 9 ----- 8 1 9 2 0 5 7 3 4 6
Discussion
random_shuffle is intuitive to use. Give it a
range, and it will shuffle the range at random. There are two versions, and their
prototypes look like this:
void random_shuffle(RndIter first, RndIter last); void random_shuffle(RndIter first, RndIter last, RandFunc& rand);
In the first version, the “random” is using an implementation-specific random-number generation function, which should be sufficient for most of your needs. If it isn’t—perhaps you want a nonuniform distribution, e.g., Gaussian—you can write your own and supply that instead using the second version.
Your random-number generator must be a functor that ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access