c++ - std::mt19937 doesn't return random number -
i have following piece of code:
unsigned int randomint() { mt19937 mt_rand(time(0)); return mt_rand(); };
if call code, example 4000 times in loop, don't random unsigned integers, instead example 1000 times 1 value , next 1000 times next value.
what doing wrong?
this happens because call f
4000 times in loop, takes less mili second, @ each call time(0)
returns same value, hence initializes pseudo-random generator same seed. correct way initialize seed once , all, preferably via std::random_device
, so:
#include <random> #include <iostream> static std::random_device rd; // random device engine, based on /dev/random on unix-like systems // initialize mersennes' twister using rd generate seed static std::mt19937 rng(rd()); int dice() { static std::uniform_int_distribution<int> uid(1,6); // random dice return uid(rng); // use rng generator } int main() { for(int = 0; < 10; ++i) std::cout << dice() << " "; }