簡體   English   中英

從函數返回Boost分布生成器以在C ++中填充向量

[英]Return Boost distribution generator from function to populate vectors in C++

我有以下函數應返回分布生成器,以便可以使用該函數填充向量,即

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());});
}

我特別需要此功能,因為我將有一個參數化函數來生成要以這種方式使用的多個分布。 請提出我到底需要做些什么。

您可以使用boost::function<> (甚至是std::function<> ):

生活在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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM