c++randomstlstdvectoruniform-initialization

Initialize an N-sized std::vector with std::uniform_real_distribution<double>


I have a std::vector<double> x, who's size I do not know at compile time. Assuming the size of the vector is N, I want to assign N uniformly distributed random values to it. I currently do this within a loop

std::default_random_engine generator;
std::uniform_real_distribution<double> distribution_pos(0.0,1.0);
for (auto it = x.begin(); it != x.end(); it++)
{
  *it = distribution_pos(generator);
}

This doesn't seem very elegant to me, so I was wondering if there was a smarter way to do this?


Solution

  • I would use std::generate:

    std::vector<double> x(10);
    
    std::default_random_engine gen{std::random_device{}()};
    std::uniform_real_distribution<double> dist(0.0, 1.0);
    
    std::generate(std::begin(x), std::end(x), [&]{ return dist(gen); });
    

    Note:

    You need to seed your random number generator otherwise you'll get the same sequence of numbers each time.

    I don't recommend std::default_random_engine because the Standard does not guarantee quality or reproducibility across implementations or compiler versions.