int helper( mt19937& generator ){
do stuff;
return 0;
}
#include "helper.h"
// helper function defined in separate source file and included in header
mt19937 generator(time(NULL));
int main( ) {
help(generator);
}
Is it correct to create and seed the mt19937 random number generator, then pass it by reference to a function for use?
I am doing this because I know I am suppose to only seed mt19937 once. But I have a lot of helper functions in separate source files that need to use a random number generator. E.g. with the shuffle function.
Yes it is correct to pass the generator around by reference. The mt19937
has internal state that needs to be modified to get the next random number. If you were to pass the generator by value then you would make a copy of that state and then multiple functions would wind up getting the same random number. This is also why you cannot pass it by const&
since it would not be able to modify that internal state if it was const
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With