Last active
March 8, 2021 11:28
-
-
Save Bktero/70cbcece6f001cb63814b8db49326ad6 to your computer and use it in GitHub Desktop.
[C++] Simple function to get random numbers in modern C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <random> | |
template<typename T> | |
T random(T min = 0, T max = std::numeric_limits<T>::max()) { | |
static std::random_device randomDevice; | |
static std::mt19937 mersenneTwisterEngine(randomDevice()); | |
std::uniform_int_distribution<T> distribution{min, max}; | |
return distribution(mersenneTwisterEngine); | |
} | |
int main() { | |
for (int i = 0; i < 5; ++i) { | |
std::cout << random<int>(-100, 100) << '\t'; | |
} | |
for (int i = 0; i < 5; ++i) { | |
std::cout << random<char>() << '\t'; | |
} | |
} |
See also https://stackoverflow.com/a/66495060/12342718 : std::random_device
may not have entropy and then using the current time as seed is a possible alternative.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simpler version of the
random
version is possible:However, using a Mersenne Twister engine may probably result in faster code. See https://stackoverflow.com/a/38368609/12342718