Duplicate values ​​from std :: uniform_int_distribution

I don’t understand what is going on here.

#include <iostream>
#include <random>
#include <chrono>
using namespace std;

unsigned number_in_range(unsigned, unsigned, default_random_engine);

int main()
{

    time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now());

    default_random_engine rng(now);

    //
    // Print out 10 random numbers
    //
    for (int i = 0; i < 10; i++)
    {
        uniform_int_distribution<int> dist(0, 100);
        cout << dist(rng) << endl;
    }

    cout << endl;

    //
    // Do the same thing, but get the numbers from `number_in_range()`
    //
    for (int i = 0; i < 10; i++)
    {
        cout << number_in_range(0, 100, rng) << endl;
    }

    return 0;
}

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine rng)
{
    uniform_int_distribution<int> dist(range_start, range_end);
    return dist(rng);
}

An example of the output of this code:

45
21
10
3
54
18
23
72
68
27

68
68
68
68
68
68
68
68
68
68

number_in_range()works exactly the same as the code in my first for loop, and yet it repeats the same value over and over. What is different from the version number_in_range()and how can I fix it?

+4
source share
1 answer

You are copying a random engine instead of referencing it. Therefore, he always has the same internal state.

Try:

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine &rng)
+12
source

Source: https://habr.com/ru/post/1670289/


All Articles