Function not updating internal state of mt19937

I have a function that generates and writes random integers:

void randint(int min, int max, int times,std::mt19937 rng){

    std::uniform_int_distribution<int> dist(min, max);

    for (int i=0;i<times;i++){
        std::cout<<dist(rng)<<' ';
    }
}

When this function is called, generates numbers from the mt19937 object. However, when returning from the function, the mt19937 object’s internal state is not updated.

This can be seen by running this code below.

int main(){
    std::mt19937 gen(2845);
    std::uniform_int_distribution<int> spread(1,100);

    randint(1,100,5,gen);

    std::cout<<"| ";

    for (int i=0;i<5;i++){
        std::cout<<spread(gen)<<' ';
    }

Actual Output:

88 93 79 43 92 | 88 93 79 43 92

Expected output:

88 93 79 43 92 | 97 71 34 32 70

Is there any way for the internal state to be continuously updated even when passed through the function?

>Solution :

You are passing the object by value (i.e. you are copying the object when you call the function). Use a reference

void randint(int min, int max, int times,std::mt19937& rng){

Leave a Reply