我下面的代码受线程“Does std::mt19937 require warmup?”的影响。执行时,会生成两个内容相同的 vector ,这不是我想要的。我期望两个 vector 中的内容不同。我做错了什么以及如何解决?
输出:
0.251423
0.729274
-1.43542
0.251423
0.729274
-1.43542
代码:
#include <vector>
#include <algorithm>
#include <iostream>
#include <random>
#include <array>
#include <functional>
#include <iterator>
class functor1
{
public:
functor1()
{
std::random_device device;
std::array<int, std::mt19937::state_size> seeds;
std::generate_n(seeds.data(), seeds.size(), std::ref(device));
std::seed_seq sequence(std::begin(seeds), std::end(seeds));
engine.seed(sequence);
}
double operator()()
{
std::normal_distribution<double> distribution(0.0, 1.0);
return distribution(engine);
}
private:
std::mt19937 engine;
};
int main()
{
functor1 f1;
std::vector<double> v0;
std::vector<double> v1;
std::generate_n(std::back_inserter(v0), 3, f1);
std::generate_n(std::back_inserter(v1), 3, f1);
std::ostream_iterator<double> out(std::cout, "\n");
std::copy(v0.begin(), v0.end(), out);
std::copy(v1.begin(), v1.end(), out);
}
谢谢
最佳答案
这是因为 f1
被复制到 generate_n()
函数调用中。使用 std::ref(f1)
代替,它将为 v0
和 v1
返回不同的结果:
std::generate_n(std::back_inserter(v0), 3, std::ref(f1));
std::generate_n(std::back_inserter(v1), 3, std::ref(f1));
关于c++ - 如何使用 std::mt19937 避免相同的随机结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365422/