Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct to pass the random number generator mt19937 by reference to helper functions?

Tags:

c++

random

c++11

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.

like image 298
Legendre Avatar asked Mar 10 '23 09:03

Legendre


1 Answers

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.

like image 157
NathanOliver Avatar answered Mar 16 '23 00:03

NathanOliver