[英]Repeated values from std::uniform_int_distribution
I don't understand what's 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 is: 此代码的输出示例如下:
45
21
10
3
54
18
23
72
68
27
68
68
68
68
68
68
68
68
68
68
number_in_range()
works in exactly the same way as the code in my first for loop, and yet it spits out the same value over and over again. number_in_range()
工作方式与我的第一个for循环中的代码完全相同,但它反复吐出相同的值。 What's different about the number_in_range()
version, and how can I fix it? number_in_range()
版本有什么不同,我该如何解决?
You are copying the random engine instead of taking a reference to it. 您正在复制随机引擎而不是引用它。 Hence, it always has the same internal state.
因此,它始终具有相同的内部状态。
Try: 尝试:
unsigned number_in_range(unsigned range_start, unsigned range_end, default_random_engine &rng)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.