Use std::random_device
to generate the seed. It'll provide non-deterministic random numbers, provided your implementation supports it. Otherwise it's allowed to use some other random number engine.
std::mt19937_64 prng;
seed = std::random_device{}();
prng.seed(seed);
operator()
of std::random_device
returns an unsigned int
, so if your platform has 32-bit int
s, and you want a 64-bit seed, you'll need to call it twice.
std::mt19937_64 prng;
std::random_device device;
seed = (static_cast<uint64_t>(device()) << 32) | device();
prng.seed(seed);
Another available option is using std::seed_seq
to seed the PRNG. This allows the PRNG to call seed_seq::generate
, which produces a non-biased sequence over the range [0 ≤ i < 232), with an output range large enough to fill its entire state.
std::mt19937_64 prng;
std::random_device device;
std::seed_seq seq{device(), device(), device(), device()};
prng.seed(seq);
I'm calling the random_device
4 times to create a 4 element initial sequence for seed_seq
. However, I'm not sure what the best practice for this is, as far as length or source of elements in the initial sequence is concerned.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…