来自std :: uniform_int_distribution的重复值

Mic*_*rst 4 c++ random c++11

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

#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);
}
Run Code Online (Sandbox Code Playgroud)

此代码的输出示例如下:

45
21
10
3
54
18
23
72
68
27

68
68
68
68
68
68
68
68
68
68
Run Code Online (Sandbox Code Playgroud)

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

Rém*_*net 12

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

尝试:

unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine &rng)
Run Code Online (Sandbox Code Playgroud)

  • @anthropomorphic [我想这个数字每20分钟就会改变一次?](http://stackoverflow.com/questions/32730906/random-generates-same-number-in-linux-but-not-in-windows/32731387 #32731387) (2认同)