A random number engine produces a deterministic pseudorandom sequence from a seed, internal state, and generation algorithm. A distribution transforms engine output into useful results such as integers from 1 through 100. section 3.2.1
Use an engine together with a distribution:
- Seed the engine, commonly with std::random_device. section 3.2.1
- Choose an engine such as std::mt19937. section 3.2.1
- Choose a distribution, such as std::uniform_int_distribution<int>, to specify the desired range or probability behavior. section 3.2.1
- Call dist(engine) for each value; setup is normally performed once and the engine continues from its remembered state. section 3.2.2
A guessing-game number
A small function can create a random number from 1 through 100: construct std::random_device, seed std::mt19937, construct the integer distribution, and return dist(engine). The guessing game then receives that value instead of a fixed constant. section 3.2.2
Listing 3.9 Generating a single random number
int some_random_number()
{
std::random_device rd; #1
std::mt19937 engine(rd()); #2
std::uniform_int_distribution<int> dist(1, 100); #3
return dist(engine); #4
}
Inspect the complete single-number implementation, including engine construction, seeding, range selection, and distribution invocation. section 3.2.2
