lundi 15 janvier 2018

Why does using std::generate to fill a vector with random data always produce the same content?

I am trying to fill a std::vector with random data using the following code (based on this answer):

std::mt19937 mersenne_engine(time(NULL));
std::uniform_int_distribution<unsigned int> distribution(1, 10);
auto generator = std::bind(distribution, mersenne_engine);

for(unsigned int i=0; i<10; ++i) {
    std::vector<unsigned int> weights(10);

    // This line always generates the same vector content.
    std::generate(weights.begin(), weights.end(), generator);
    // This line properly randomizes the content each iteration.
    //for(auto &weight : weights) weight = generator();

    for(auto &weight : weights) {
        std::cout << weight << " ";
    }
    std::cout << std::endl;
}

ideone

For some reason this generates the same vector contents for each of the 10 iterations. Generating the weights manually (commented out line) works just fine.

What am I doing wrong here?




Aucun commentaire:

Enregistrer un commentaire