我的代码受线程" Does std::mt19937 require warmup?"的影响。执行时,生成两个具有相同内容的向量,这不是我想要的。我预计两个载体中的内容都不同。我做错了什么以及如何解决它?
输出:
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);
}
由于
答案 0 :(得分:7)
这是因为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));