【问题标题】:Return Boost distribution generator from function to populate vectors in C++从函数返回 Boost 分布生成器以在 C++ 中填充向量
【发布时间】:2015-07-30 05:45:26
【问题描述】:

我有以下函数应该返回一个分布生成器,这样我就可以使用该函数来填充一个向量,即

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

我特别需要这种能力,因为我将有一个参数化函数来生成以这种方式使用的多个分布。请建议 我到底需要做什么才能实现这一目标。

【问题讨论】:

  • 什么是T3? gen 来自哪里? new_func 是否应该将其与分布参数一起作为参数接收?请创建一个SSCCE
  • 我不明白为什么这个问题被否决了。我假设人们不知道分布是什么。是的,问题的措辞很笨拙,但至少伪代码很有启发性

标签: c++ c++11 boost vector


【解决方案1】:

你可以使用boost::function&lt;&gt;(甚至std::function&lt;&gt;):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    相关资源
    最近更新 更多