我正在使用GCC 4.6.3并尝试使用以下代码生成随机数:
#include <random>
#include <functional>
int main()
{
std::mt19937 rng_engine;
printf("With bind\n");
for(int i = 0; i < 5; ++i) {
std::uniform_real_distribution<double> dist(0.0, 1.0);
auto rng = std::bind(dist, rng_engine);
printf("%g\n", rng());
}
printf("Without bind\n");
for(int i = 0; i < 5; ++i) {
std::uniform_real_distribution<double> dist(0.0, 1.0);
printf("%g\n", dist(rng_engine));
}
return 0;
}
我希望这两种方法都能生成5个随机数的序列。相反,这就是我实际得到的:
With bind
0.135477
0.135477
0.135477
0.135477
0.135477
Without bind
0.135477
0.835009
0.968868
0.221034
0.308167
这是GCC的错误吗?或者是与std :: bind有关的一些微妙问题?如果是这样,你能对结果有所了解吗?
感谢。
答案 0 :(得分:12)
绑定时,会生成rng_engine的副本。如果您想传递参考,那么您必须这样做:
auto rng = std::bind(dist, std::ref(rng_engine));
答案 1 :(得分:5)
std::uniform_real_distribution::operator()
需要Generator &
,因此您必须使用std :: ref
#include <random>
#include <functional>
int main()
{
std::mt19937 rng_engine;
printf("With bind\n");
for(int i = 0; i < 5; ++i) {
std::uniform_real_distribution<double> dist(0.0, 1.0);
auto rng = std::bind(dist, std::ref(rng_engine));
printf("%g\n", rng());
}
printf("Without bind\n");
for(int i = 0; i < 5; ++i) {
std::uniform_real_distribution<double> dist(0.0, 1.0);
printf("%g\n", dist(rng_engine));
}
}
答案 2 :(得分:2)
bind()
用于重复使用。
把它放在循环之外...
std::mt19937 rng_engine;
std::uniform_real_distribution<double> dist(0.0, 1.0);
auto rng = std::bind(dist, rng_engine);
for(int i = 0; i < 5; ++i) {
printf("%g\n", rng());
}
...给了我预期的结果:
0.135477
0.835009
0.968868
0.221034
0.308167