我不明白这里发生了什么。

#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);
}

此代码的输出示例是:
45
21
10
3
54
18
23
72
68
27

68
68
68
68
68
68
68
68
68
68
number_in_range() 的工作方式与我第一个 for 循环中的代码完全相同,但它一遍又一遍地输出相同的值。 number_in_range() 版本有什么不同,我该如何解决?

最佳答案

您正在复制随机引擎而不是引用它。因此,它始终具有相同的内部状态。

尝试:

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine &rng)

关于c++ - 来自 std::uniform_int_distribution 的重复值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42344275/

10-10 00:59