How do I use random number facilities in C++?

C++ provides a variety of facilities for generating random numbers, which can be useful for simulations, games, and other applications that require randomization. The standard library offers tools for generating random numbers through the random header, where you can utilize different distributions and engines to create random values.

Generating Random Numbers in C++

To generate random numbers in C++, you typically include the random header and use a random number engine together with a distribution. Here's a simple example:

#include <iostream> #include <random> int main() { // Initialize a random number engine std::random_device rd; // Get a random number from hardware std::mt19937 eng(rd()); // Seed the engine // Define the range (1 to 100) std::uniform_int_distribution<int> distr(1, 100); // Generate and print random numbers std::cout << "Random numbers:\n"; for (int n = 0; n < 10; ++n) { std::cout << distr(eng) << ' '; } return 0; }

C++ random number generation standard library random number engine uniform distribution