高效升压分配使用(Efficient boost distribution usage)

2019-07-29 15:40发布

(改写的问题)

我创建了升压正态分布一个包装类,并想使之尽可能高效。

如果我使用:

double x = 0.0;
boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor(rng, nd);
for (int i=0; i<20; i++) {
     double x = var_nor();
}

循环工作正常。 我担心的是我不想被不必要地宣布任何的方法被调用多次。 我试图分裂了代码,并把这个线在构造函数:

boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor(rng, nd);

并具有执行此的样品的方法:

     double x = var_nor();
     return x;

但是,在这种情况下,我得到一个错误说var_nor()(即不带参数)未找到。 谁能告诉我这是怎么回事这些升压声明即。 什么是

提高:variate_generate等。

线实际上var_nor做? 用我有限的C ++知识,它看起来好像var_nor正在用两种不同的签名定义。

感谢球员皮特

Answer 1:

在你的代码, var_nor是一个变量 ,而不是一个功能,因此它不具有签名。 它代表了variate_generator对象,可以表现得像一个功能,因为它支持operator()

在代码中,你声明并初始化var_nor在同一时间。 该rngnd参数传递给的构造函数 variate_generator对象。

当你移动的声明到类的构造函数,你被宣布var_nor在构造函数中的局部变量 ,所以这也难怪它是其他地方没有的。 对于贯穿整个班级可用的东西,它需要一个成员变量 。 声明它在类私有:

class NormalDistribution
{
  boost::random::mt19937 _rng;
  boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor;
public:
  NormalDistribution();
};

然后在构造函数初始化它:

NormalDistribution::NormalDistribution():
  _rng(), var_nor(_rng, boost::normal_distribution<>(0.0, 1.0))
{ }

_rng成员首先需要声明,以便它将首先被初始化。 该nd参数可以被省略,并且用临时替换normal_distribution直接传递给对象var_nor如上所示的构造。

这些变化,你应该能够使用相同的normal_distribution对象在多个调用你的sample函数,或任何其他用途你有你的NormalDistribution类。

在你已经因为从你的问题中删除代码,你混淆变量声明与函数声明。 你发起了nd作为函数接收两个参数并返回一个normal_distribution 。 同样与var_nor 。 这是一个功能,当你真的想要的对象。 你感到困惑,因为它正好是就像一个函数的对象,但它仍然只是一个对象。



Answer 2:

OK,工作使用罗伯肯尼迪的回答最终版本,其他人可能会感兴趣:

// normaldistribution.h
#ifndef NORMALDISTRIBUTION_H
#define NORMALDISTRIBUTION_H

#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>
class NormalDistribution
{
 public:
    NormalDistribution();
    double sample(void);
 private:
    // Use the boost random number generator
    boost::mt19937 rng;
    // Make a variate_generator OBJECT.
    boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > var_nor;
};

#endif // NORMALDISTRIBUTION_H

// normaldistribution.cpp
NormalDistribution::NormalDistribution():
  rng(), var_nor(rng, boost::normal_distribution<>(0.0, 1.0))
{
    std::cout << "Called normal distribution constructor, passing up var_nor" << std::endl;
}

double NormalDistribution::sample(void) {
    double x = var_nor();
    return x;
}

// main.cpp
#include "normaldistribution.h"

int main(int argc, char *argv[])
{
    NormalDistribution *nd = new NormalDistribution();
    for (int i=0; i < 10; ++i)
    {
      double d = nd->sample();
      std::cout << d << std::endl;
    }
    return 0;
}


文章来源: Efficient boost distribution usage