c++ - 无法在 Visual C++ 2010 中使用 default_random_engine 字段创建类

标签 c++ visual-c++ random

我尝试创建一个具有default_random_engine 私有(private)字段的类。但是,这个类无法编译。我的简单控制台程序代码如下:

// RngTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <ctime>
#include <random>

using namespace std;

class MyClass
{
private:
    default_random_engine Rng;
public:
    MyClass(void)
        : Rng(time(NULL))
    {
    }
    ~MyClass(void)
    {
    }
    void Seed(unsigned int seed)
    {
        Rng.seed(seed);
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    MyClass rng;
    rng.Seed(100);
    return 0;
}

在 Visual Studio 2010(静态标准库,无 MFC/ATL,控制台项目)中,我看到以下编译错误:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\random(1604): error C2064: term does not evaluate to a function taking 0 arguments 1>
c:\users\vitaliy\documents\visual studio 2010\projects\rngtest\rngtest\rngtest.cpp(25) : see reference to function template instantiation 'void std::tr1::mersenne_twister<_Ty,_Wx,_Nx,_Mx,_Rx,_Px,_Ux,_Sx,_Bx,_Tx,_Cx,_Lx>::seed(_Gen &,bool)' being compiled

编译失败可能是什么原因?有没有办法在 Visual C++ 2010 中使用 default_random_engine 私有(private)字段?

最佳答案

我花了大约 4 个小时试图解决这个问题。万一其他人遇到这个...

default_random_generator 将采用 unsigned long 类型的种子。 Int、unsigned int、长短字节双字不会削减它。它必须是无符号整数。

另请注意,您不能以 0 为种子,否则会出现运行时错误。以下是我来之不易的编译代码...

unsigned long seed = pblock->GetInt(p_seed);
// We cannot seed with 0, so increment by 1 to avoid the error
seed++;
std::default_random_engine generator(seed);

关于c++ - 无法在 Visual C++ 2010 中使用 default_random_engine 字段创建类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17013242/

相关文章:

algorithm - 具有均匀分布的随机可变长度编码数字

php - 如何实现随机浮点函数使其不丢失熵? (PHP)

c++ - 在模板化类的模板化构造函数中扩展参数包

c++ - 在 C++ 中将代码分解为几个小函数有什么好处?

c++ - 如何使用 char* 调用带有 string& 参数的方法?

python - 弄清楚非均匀随机算法的工作原理

c++ - 在构造函数C++中初始化属性时出现问题

c++ - 将深度缓冲区渲染为纹理的管道可能存在什么问题?

c++ - 封闭范围

c - memcpy() 和 memset() 的奇怪行为