Random Numbers with <random> in C++
The <random> library separates generation into engines (the raw source, e.g. std::mt19937 seeded once) and distributions (shaping: uniform_int_distribution, normal_distribution, shuffle). This beats rand()%N on every axis — statistical quality, range correctness (no modulo bias), and reproducibility via explicit seeds.
Seed once per program (std::random_device, or a fixed seed for deterministic tests), then draw repeatedly. Threading? Engines aren't thread-safe — give each thread its own. For shuffling, std::shuffle with your engine replaces hand-rolled swaps.
Engine plus distribution
std::mt19937 rng(seed); produces raw bits; std::uniform_int_distribution<int> d(1, 6); shapes them into dice rolls.
Seed deliberately
std::random_device for real randomness, fixed constants for reproducible tests — never re-seed per draw.
No modulo bias
rand() % n skews toward low values; distributions map ranges uniformly by construction.
Shuffle properly
std::shuffle(v.begin(), v.end(), rng); permutes uniformly — the correct Fisher-Yates, not a sorting hack.
#include <iostream>#include <random> int main() { std::mt19937 rng(42); std::uniform_int_distribution<int> dice(1, 6); std::cout << dice(rng) << ", " << dice(rng) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.