Random Number Generator in C++
To generate a random number in C++, you can use the
#include <iostream>
#include <random>
int main() {
// Random number generator
std::random_device rd; // Obtain a random number from hardware
std::mt19937 gen(rd()); // Seed the generator
std::uniform_int_distribution<> distr(1, 10); // Define the range
// Generate and print a random integer between 1 and 10
std::cout << "Random Number: " << distr(gen) << std::endl;
return 0;
}
In this code:
- std::random_device is used to obtain a truly random number from your system's hardware (if available).
- std::mt19937 is a Mersenne Twister pseudo-random generator used to generate high-quality random numbers. It's seeded with the value obtained from std::random_device.
- std::uniform_int_distribution defines a uniform distribution in the range [1, 10]. When used with a random number generator, it produces random integers in the specified range, inclusive.
- distr(gen) generates a new random integer in the specified range each time it's called.
This approach is more flexible and preferable for modern C++ applications compared to older methods like rand().