Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Memory and Utilities

The C++ <random> header

Overview of the C++ <random> library: random_device, engines like mt19937, distributions, seeding for reproducible runs, and why rand() falls short.

The <random> header (C++11) splits random number generation into two parts. A random engine such as std::mt19937 produces a stream of raw pseudo-random integers from a seed. A distribution such as std::uniform_int_distribution turns those raw numbers into values with the shape you want: a fair die, a bell curve, a coin that lands heads 30% of the time. You combine them: dist(engine).

std::random_device is the third piece: a source of non-deterministic numbers used mainly to seed an engine. Compared with the C function rand(), this design gives better quality, larger ranges, correct (unbiased) ranges, per-object state with no hidden global, and generators you can reproduce on demand.

C++
std::mt19937 gen{std::random_device{}()};
std::uniform_int_distribution<int> die{1, 6};
int roll = die(gen);

Try it

C++ Engine plus distribution, reproducibly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Seeding with random_device and picking items

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
#include <random>

std::random_device rd;                         // non-deterministic source
std::mt19937 gen{seed};                        // engine
std::uniform_int_distribution<int> d{lo, hi};  // distribution
int value = d(gen);
Component Description
std::random_device Uniform integer source, possibly hardware- or OS-backed; used to produce seeds.
Engines mt19937, mt19937_64, minstd_rand, ranlux24, knuth_b, default_random_engine.
Distributions uniform_int_distribution, uniform_real_distribution, normal_distribution, bernoulli_distribution, discrete_distribution, and more.
std::seed_seq Mixes several integers into a well-spread engine state.
std::generate_canonical<R, bits>(gen) A real in [0, 1) from an engine.

Returns: engines return unsigned integers via operator(); distributions return values of their result type.

Errors / undefined behavior: uniform_int_distribution{a, b} requires a <= b; uniform_real_distribution{a, b} requires a < b and a finite range; violating this is undefined. random_device may throw std::runtime_error if no source exists, and on some platforms it is deterministic.

Usage notes

  • Seed once. Create the engine once (for example one per thread) and reuse it. Re-seeding in a loop from the clock repeats values.
  • Never % n an engine's output to get a range: the result is biased. Use a distribution.
  • Engines are not thread-safe. Give each thread its own engine, or lock a shared one.
  • Reproducibility: engine sequences for a given seed are specified by the standard (for mt19937, minstd_rand and the others), so tests can rely on them. Distribution outputs are not specified: libstdc++, libc++ and MSVC produce different values from the same engine state, so do not hard-code expected numbers for distributions.
  • std::mt19937 seeded with one 32-bit number has limited entropy. For better seeding, fill it from a std::seed_seq made of several random_device outputs.
  • Not for security. These generators are predictable; use an operating-system CSPRNG for keys, tokens and passwords.
  • std::default_random_engine is implementation-defined and can differ between compilers; choose mt19937 when you care.
  • Shuffle and sample: std::shuffle takes an engine; std::sample (C++17) picks n elements without replacement.
  • std::random_shuffle and rand() are deprecated or removed (random_shuffle was removed in C++17); do not use them in new code.