Reputation: 1008
My code below is influenced by thread "Does std::mt19937 require warmup?". When executed, two vectors are generated with same content what is not what I want. I've expected different content in both vectors. What am I doing wrong and how to fix it?
Output:
0.251423
0.729274
-1.43542
0.251423
0.729274
-1.43542
Code:
#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);
}
Thanks
Upvotes: 2
Views: 716
Reputation: 18228
This is because f1
is copied into generate_n()
function invocation. Use std::ref(f1)
instead and it will return different results for v0
and v1
:
std::generate_n(std::back_inserter(v0), 3, std::ref(f1));
std::generate_n(std::back_inserter(v1), 3, std::ref(f1));
Upvotes: 7