Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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){
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading