liveBook · Manning

Random number engine

As explained in Learn C++ by Example

A random number engine is a pseudorandom generator component that produces a deterministic sequence from an internal state and algorithm.

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

How Learn C++ by Example covers it

How deep it goes
Explains seeding, remembered state, periods, distributions, and repeated calls, while deferring detailed distribution study.
Examples
Demonstrates a guessing game, a deliberately alternating generator, and a 1-to-100 uniform integer distribution.
What it assumes
Assumes basic C++ functions and calls while introducing seeds, engines, distributions, and pseudorandom generation from first principles.
What you can do after
Apply it via std::random_device, std::mt19937, and a distribution to generate bounded pseudorandom values.
How it connects
Connects engines with seeds, pseudorandom number generators, probability distributions, uniform_int_distribution, random_device, and rejection sampling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.