0

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?

zennehoy
  • 6,405
  • 28
  • 55
  • `std::bind` makes a copy of `distribution` and `mersenne_engine`; and then `std::generate` makes a copy of generator. Try using `std::ref` to avoid this problem. – Mankarse Jan 15 '18 at 09:11
  • 1
    @Mankarse Nice catch, that was in fact the problem. Do you want to make an answer of it? – zennehoy Jan 15 '18 at 09:14
  • @WernerHenze Yup, I found that same question once I knew what the problem was :) – zennehoy Jan 15 '18 at 09:38

0 Answers0