Skip to content

Instantly share code, notes, and snippets.

@Bktero
Last active March 8, 2021 11:28
Show Gist options
  • Save Bktero/70cbcece6f001cb63814b8db49326ad6 to your computer and use it in GitHub Desktop.
Save Bktero/70cbcece6f001cb63814b8db49326ad6 to your computer and use it in GitHub Desktop.
[C++] Simple function to get random numbers in modern C++
#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';
}
}
@Bktero
Copy link
Author

Bktero commented Mar 8, 2021

A simpler version of the random version is possible:

template<typename T>
T random(T min = 0, T max = std::numeric_limits<T>::max()) {
	std::random_device randomDevice;
	std::uniform_int_distribution<T> distribution{min, max};
	return distribution(randomDevice);
}

However, using a Mersenne Twister engine may probably result in faster code. See https://stackoverflow.com/a/38368609/12342718

@Bktero
Copy link
Author

Bktero commented Mar 8, 2021

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