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.
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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?