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.
std::mt19937 gen{std::random_device{}()}; std::uniform_int_distribution<int> die{1, 6}; int roll = die(gen);
Try it
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.
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
#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
% nan 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_randand 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::mt19937seeded with one 32-bit number has limited entropy. For better seeding, fill it from astd::seed_seqmade of severalrandom_deviceoutputs.- Not for security. These generators are predictable; use an operating-system CSPRNG for keys, tokens and passwords.
std::default_random_engineis implementation-defined and can differ between compilers; choosemt19937when you care.- Shuffle and sample:
std::shuffletakes an engine;std::sample(C++17) picks n elements without replacement. std::random_shuffleandrand()are deprecated or removed (random_shufflewas removed in C++17); do not use them in new code.