C++ Random
Randomness plays a critical role in many programming tasks, including simulations, games, cryptography, and testing. In C++, generating random numbers has evolved significantly with the introduction of the <random> library in C++11, offering more powerful and flexible tools than the traditional C-style rand() function.
Traditional Approach: rand()
Before C++11, randomness was handled using the C standard library function rand().
This example uses the rand() function to generate a random number:
#include <iostream>#include <cstdlib>#include <ctime>int main() {std::srand(std::time(nullptr)); // Seed with the current timeint random_number = std::rand(); // Generate a random numberstd::cout << "Random Number: " << random_number << '\n';return 0;}
In this example:
rand(): Returns a random number between 0 andRAND_MAX.srand(): Initializes the random number generator with a seed.
Here is a possible output:
Random Number: 1950498172
Note: Since the number is randomly generated, the output may vary each time the code is run.
Modern Approach: <random>
The <random> header, introduced in C++11, provides a robust framework for random number generation.
Here are the key components of this header:
- Engines: Generate raw random numbers.
- Distributions: Transform raw numbers into specific ranges or statistical distributions.
Common Distributions
| Distribution Type | Class Name | Description |
|---|---|---|
| Uniform (integers) | std::uniform_int_distribution |
Evenly distributed integers in a given range |
| Uniform (real numbers) | std::uniform_real_distribution |
Evenly distributed floating-point values |
| Normal (Gaussian) | std::normal_distribution |
Bell curve (Gaussian) distribution |
| Bernoulli | std::bernoulli_distribution |
true or false with a given probability |
| Binomial | std::binomial_distribution |
Number of successes in a fixed number of trials |
Example
This example uses the <random> header to generate a random number between 1-6:
#include <iostream>#include <random>int main() {std::random_device rd; // Seedstd::mt19937 gen(rd()); // Mersenne Twister enginestd::uniform_int_distribution<> dist(1, 6); // Uniform distribution [1, 6]std::cout << "Rolling a dice: " << dist(gen) << '\n';return 0;}
In this example:
std::random_device: Non-deterministic seed generator (may fall back to pseudo-random).std::mt19937: High-quality pseudo-random number generator (Mersenne Twister).std::uniform_int_distribution: Ensures even distribution between two bounds.
Here is a possible output:
Rolling a dice: 2
Codebyte Example: Ranged Random Number Generator Using rand()
This codebyte example uses the rand() function to generate a random number in the range 10-50:
In this example:
std::rand() % (upper - lower + 1)gives a number between 0 and(upper - lower).- Adding
lowershifts the range to[lower, upper]. srand()ensures different results across runs by seeding with the current time.
Best Practices for Generating Random Numbers
- Prefer
<random>overrand()for better control and randomness. - Use
std::random_devicefor seeding when unpredictability is desired. - Match engines with appropriate distributions for accurate simulations.
- Avoid using the same engine across multiple threads without synchronization.
Frequently Asked Questions
1. What’s the difference between rand() and <random> in C++?
rand()is a legacy function from C that returns a pseudo-random number.<random>, introduced in C++11, offers modern, flexible, and statistically sound ways to generate random numbers using engines and distributions.
2. Why should I avoid using rand() in serious applications?
- Poor randomness quality.
- Predictable if seeded with the same value.
- Not thread-safe.
- No control over distributions.
Use <random> for better randomness and control.
3. Is <random> thread-safe?
No. You should use separate engines per thread or protect shared engines with mutexes.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours