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>
:
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)
Distributions:
- Shape the raw output of engines into specific probability distributions.
- Examples:
std::uniform_int_distribution
: Generates uniformly distributed integers within a rangestd::uniform_real_distribution
: Generates uniformly distributed real numbers within a rangestd::normal_distribution
: Generates normally distributed real numbersstd::bernoulli_distribution
: Generates Boolean values (true or false) with a specified probability- And more...
Basic usage:
Include the header:
C++#include <random>
Create an engine:
C++std::mt19937 engine; // Mersenne Twister engine
Seed the engine (for non-deterministic results):
C++std::random_device rd; engine.seed(rd());
Create a distribution:
C++std::uniform_int_distribution<int> dist(1, 6); // Generate integers from 1 to 6
Generate random numbers:
C++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.
Remember:
- Use
#include <random>
instead ofrand()
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.