liveBook · Manning

Mersenne Twister

As explained in Learn C++ by Example

mt19937 is a C++ standard library pseudorandom number engine implementing the Mersenne Twister algorithm with a period of 2^19937−1.

MT19937 is a C++ pseudorandom number engine based on the Mersenne Twister algorithm. It produces a long repeating sequence with period 2^19937−1, making it far more useful than a generator that alternates between two values. section 3.2.1

Use an engine with a seed and a distribution. A fixed seed reproduces the same sequence, which helps simulations and testing; random_device can instead provide a seed intended to vary between runs. uniform_int_distribution then maps engine output into a requested range. section 3.2.1 section 3.2.2

A number for a guessing game

Create random_device rd, initialize std::mt19937 engine(rd()), create std::uniform_int_distribution<int> dist(1, 100), and return dist(engine). Call the function from a guessing game to choose its hidden number. 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
}

Shows the complete engine, seed, distribution, and generated-value setup for one random integer. section 3.2.2

How Learn C++ by Example covers it

How deep it goes
Explains periods, seeds, engines, and distributions, then demonstrates one generated integer without developing the algorithm’s internals.
Examples
Uses a deliberately poor alternating generator, a 1–100 integer generator, and a random-number guessing game.
What it assumes
Assumes basic C++ functions and integers while teaching engine, seed, and distribution setup from practical examples.
What you can do after
Apply it via std::random_device, std::mt19937, and std::uniform_int_distribution to generate bounded integers.
How it connects
Connects pseudorandom number generators with seeds, random_device, uniform_int_distribution, simulations, and testing.

Also explained in

Compare how 2 books explain Mersenne Twister →

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.