In C++, what is #include <random>?

In C++, #include <random> is a header file that provides facilities for generating random numbers. It offers a powerful and flexible framework for generating various types of random sequences, addressing the limitations of the older rand() function.

Key components of <random>:

  1. Engines:

    • Generate sequences of pseudo-random numbers, acting as the base for random number production.
    • Examples:
      • std::mt19937: Mersenne Twister engine (widely used, good quality)
      • std::minstd_rand: Minimal Standard engine (smaller and faster, but lower quality)
      • std::random_device: Non-deterministic engine for seeding other engines (uses hardware sources for randomness)
  2. Distributions:

    • Shape the raw output of engines into specific probability distributions.
    • Examples:
      • std::uniform_int_distribution: Generates uniformly distributed integers within a range
      • std::uniform_real_distribution: Generates uniformly distributed real numbers within a range
      • std::normal_distribution: Generates normally distributed real numbers
      • std::bernoulli_distribution: Generates Boolean values (true or false) with a specified probability
      • And more...

Basic usage:

  1. Include the header:

    #include <random>
  2. Create an engine:

    std::mt19937 engine;  // Mersenne Twister engine
  3. Seed the engine (for non-deterministic results):

    std::random_device rd;
  4. Create a distribution:

    std::uniform_int_distribution<int> dist(1, 6);  // Generate integers from 1 to 6
  5. Generate random numbers:

    int random_number = dist(engine);

Advantages over rand():

  • More flexible: Offers a variety of engines and distributions for different needs.
  • Better quality: Produces higher-quality random sequences compared to rand().
  • Non-deterministic: Can be seeded with non-deterministic sources for true randomness.
  • Extensible: Allows for custom engines and distributions.


  • Use #include <random> instead of rand() for modern C++ random number generation.
  • Choose the appropriate engine and distribution based on your specific requirements.
  • Seed the engine properly for non-deterministic results.
You should also read: