< Previous | Contents | Next >

Using the random_shuffle() Algorithm

Next I prepare to randomize the scores using the random_shuffle() algorithm. Just as when I generate a single random number, I seed the random number generator before I call random_shuffle(), so the order of the scores might be different each time I run the program.

srand(static_cast<unsigned int>(time(0)));

Then I reorder the scores in a random way.

random_shuffle(scores.begin(), scores.end());

Using Algorithms 135


The random_shuffle() algorithm randomizes the elements of a sequence. You must supply as iterators the starting and ending points of the sequence to shuffle. In this case, I passed the iterators returned by scores.begin() and scores.end(). These two iterators indicate that I want to shuffle all of the elements in scores. As a result, scores contains the same scores, but in some random order.

Then I display the scores to prove the randomization worked.


Tric k

image

Although you might not want to randomize a list of high scores, random_shuffle() is a valuable algorithm for games. You can use it for everything from shuffling a deck of cards to mixing up the order of the enemies a player will encounter in a game level.

image