Skip to content

Instantly share code, notes, and snippets.

@klmr
Last active November 3, 2020 21:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klmr/62863c3d9f5827df23ae2e1415b0cb1b to your computer and use it in GitHub Desktop.
Save klmr/62863c3d9f5827df23ae2e1415b0cb1b to your computer and use it in GitHub Desktop.
Correctly seed an arbitrary RNG in C++
#include <algorithm>
#include <array>
#include <functional>
#include <random>
template <typename T = std::mt19937>
auto get_random_generator() -> T {
auto constexpr seed_bytes = sizeof(typename T::result_type) * T::state_size;
auto constexpr seed_len = seed_bytes / sizeof(std::seed_seq::result_type);
auto seed = std::array<std::seed_seq::result_type, seed_len>();
auto dev = std::random_device();
std::generate_n(begin(seed), seed_len, std::ref(dev));
auto seed_seq = std::seed_seq(begin(seed), end(seed));
return T{seed_seq};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment