Return Boost distribution generator from function

2019-03-06 07:12发布

问题:

I have the following function that should return a distribution generateor such that I can use the function to populate a vector i.e.

template<typename T3>
T3 new_func()
{
    std::uniform_real_distribution<> Uni(1,2);
    boost::variate_generator< boost::mt19937, std::uniform_real_distribution<>> Uniform(gen , Uni);
    return Uniform;
}

int main ()
{
    std::vector<double> test;
    //something like
    std::for_each(test.begin(), test.end(),
         [&](std::vector<double>& a){a.push_back(new_func());});
}

I specifically need this ability as I will have a single parameterized function to generate multiple distributions to be used in this fashion. Kindly suggest what exactly I need to do achieve this.

回答1:

You can use boost::function<> (or even std::function<>):

Live On Coliru

#include <boost/math/distributions.hpp>
#include <boost/function.hpp>
#include <boost/random.hpp>
#include <random>

static boost::mt19937 gen;
typedef boost::function<double()> Distri;

Distri new_func()
{
    std::uniform_real_distribution<> Uni(1,2);
    return boost::variate_generator< boost::mt19937, std::uniform_real_distribution<>>(gen , Uni);
}

int main ()
{
    std::vector<double> test;
    //something like
    Distri d = new_func();

    //likely
    std::generate_n(back_inserter(test), 100, d);
}