0Pricing
C++ Academy · Lesson

Random Engines

Generate random bits.

Why <random>?

The old rand() is low quality and hard to control. The <random> library splits randomness into engines (sources of random bits) and distributions (shapes of output).

#include <iostream>
#include <random>

int main() {
    std::mt19937 engine(42);
    std::cout << "engine produced a value\n";
    unsigned int v = engine();
    std::cout << (v != 0 ? "non-zero" : "zero") << '\n';
    return 0;
}

The Mersenne Twister

std::mt19937 is the most common engine: fast, high quality, with a long period. The number is its state size in bits.

#include <iostream>
#include <random>

int main() {
    std::mt19937 gen(1);
    unsigned int a = gen();
    unsigned int b = gen();
    std::cout << (a != b ? "two different values" : "same") << '\n';
    return 0;
}

All lessons in this course

  1. Random Engines
  2. Distributions
  3. Seeding Properly
  4. Practical Examples
← Back to C++ Academy