【问题标题】:How to generate uniform distributed random number in VS 2010?如何在 VS 2010 中生成均匀分布的随机数?
【发布时间】:2014-06-16 18:49:27
【问题描述】:

我正在尝试创建一个包含均匀分布随机数的类。我使用 Visual Studio 2010 c++。

http://msdn.microsoft.com/en-us/library/vstudio/ee462299%28v=vs.100%29.aspx http://msdn.microsoft.com/en-us/library/ee462299.aspx

从这两个链接中尝试了许多组合,但我找不到满足我需求的解决方案。 我当前的代码是:

A) 我的问题.h

#include <random>

class MyProblem
{
public:
  int calculateMyProblem();

private:
  double _uniformRandNum;
  std::mt19937 _generator(1729);   // for 1729 I get ERROR: Expected a type specifier
  std::uniform_real_distribution<> _distribution(0,1); // for both 0 an 1 i get ERROR: Expected a type specifier
  void generateUniformDistrNum();
  void calculateMeanDistance(); 
};

对于这两行我得到了错误

error C2059: syntax error : 'constant'
error C2059: syntax error : 'constant'

B) 我的问题.cpp

MyProblem::MyProblem()
{}

int MyProblem::calculateMyProblem()
{
  generateUniformDistrNum();
  // other stuff to be done with random number _uniformRandNum

}

void MyProblem::generateUniformDistrNum() 
{
    _uniformRandNum = (double) _distribution(_generator); // ERROR, see below
}

生成的错误是:

error C3867: 'MyProblem::_generator': function call missing argument list; use '&MyProblem::_generator' to create a pointer to member

error C2660: 'MyProblem::_distribution' : function does not take 1 arguments

我尝试了一整天,现在我无法弄清楚。我该如何解决这些问题?

【问题讨论】:

  • 在 C++ 中,构造函数用于初始化对象及其成员。

标签: c++ visual-studio-2010 random


【解决方案1】:

当您使用 C++11 的非静态数据成员初始化器来初始化类定义中的数据成员时,您必须使用大括号(或等号)来进行初始化。如果您将两个违规行更改为

,您的代码将是正确的
std::mt19937 _generator{1729};
std::uniform_real_distribution<> _distribution{0,1};

Live demo

但是,这仍然无法在 VS2010 上运行(我认为您需要 VS2013 才能运行)。因此,使用该编译器的唯一选择是在构造函数的初始化程序列表中执行初始化。

MyProblem::MyProblem()
: _generator(1729)
, _distribution(0,1)
{}

【讨论】:

    【解决方案2】:

    您不能使用 () 初始化类主体中的成员(非静态或 const)。您需要在构造函数初始化列表或它的主体中(或在一个源文件中的类定义之外,如静态成员:

    头文件:

    class MyProblem
    {
    public:
      int calculateMyProblem();
    
    private:
      double _uniformRandNum;
      std::mt19937 _generator;
      std::uniform_real_distribution<> _distribution;
      void generateUniformDistrNum();
      void calculateMeanDistance(); 
    };
    

    源文件:

    MyProblem::MyProblem() : _generator( 1729), _distribution( 0, 1) {}
    //... the rest of function defs
    

    然而,在 C++11 中,您可以使用 {} 来初始化类主体中的成员:

    class MyProblem {
        //...
        std::mt19937 _generator{1729};
        std::uniform_real_distribution<> _distribution{0,1};
        //...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 2013-05-10
      • 2013-07-22
      • 2012-09-18
      相关资源
      最近更新 更多