Accessing random elements of a collection

When we have collections of similar objects, they are often stored in structures such as arrays and vectors. Usually when working with these structures we access specific elements, and it's their uniformness and order that make them useful.

To access a specific element we simply supply its index in the collection. Therefore, to access a random element of the array we just supply a random index, which is a simple case of generating a random number.

Let's have a look at an example of this. In the following example we create a vector of strings which we populate with animal names. Each time we press enter we access a random element of the vector by generating a number between 0 and the vectors size.

You can ...

Get Procedural Content Generation for C++ Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.