Also "default_random_engine" is a type def for the "mt19937" RNG. If I have said that correctly. |
Not true.
What actual generator is used for std::default_random_engine is up to the implementation/vendor, it is NOT necessarily an alias for std::mt19937. The only requirement of the C++ standard is to provide acceptable engine behavior for relatively casual, inexpert, and/or lightweight use.
http://www.cplusplus.com/reference/random/default_random_engine/
If you don't care what generator is used, std::default_random_engine is as good a choice as the others.
What if someone runs your program multiple times during that second. Then the pseudo-random number generator is seeded with the same seed, so it generates the same sequence of random numbers.
Using the system clock in <chrono> can get time intervals in the millisecond range, much finer control than what the C library time function can provide.
Another view of why using the C library for random numbers is not a good idea:
https://web.archive.org/web/20180123103235/http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/
An old C++ standard work-group paper(?) on random number generation in C++11:
http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3551.pdf
So my mistake was to initialize default_random_engine and uniform_int_distributor inside the function. |
You didn't give the object created in the function static duration, static duration would have created the object only once no matter how many times you entered the function.
https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables
A function scope variable created with static duration exists between function calls, the value is retained.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
void my_func();
int main()
{
// let's call the function several times
my_func(); my_func(); my_func(); my_func(); my_func(); my_func();
}
void my_func()
{
int a = 0;
static int b = 0;
a++; b++;
std::cout << "a: " << a << ", b: " << b << '\n';
}
| |
a: 1, b: 1
a: 1, b: 2
a: 1, b: 3
a: 1, b: 4
a: 1, b: 5
a: 1, b: 6 |
<edited to fix a rather silly typo>