繁体   English   中英

带有'std :: runtime_error'的C ++ 0x random_device

[英]C++0x random_device with 'std::runtime_error'

我是C ++初学者,我遇到了C ++ 0x随机数生成器的问题。 我想使用Mersenne twister引擎生成随机的int64_t数字,并且我使用我之前发现的一些信息编写了一个函数:

#include <stdint.h>
#include <random>

int64_t MyRandomClass::generateInt64_t(int64_t minValue, int64_t maxValue)
{
    std::random_device rd;
    std::default_random_engine e( rd() );
    unsigned char arr[8];
    for(unsigned int i = 0; i < sizeof(arr); i++)
    {
        arr[i] = (unsigned char)e();
    }
    int64_t number = static_cast<int64_t>(arr[0]) | static_cast<int64_t>(arr[1]) << 8 | static_cast<int64_t>(arr[2]) << 16 | static_cast<int64_t>(arr[3]) << 24 | static_cast<int64_t>(arr[4]) << 32 | static_cast<int64_t>(arr[5]) << 40 | static_cast<int64_t>(arr[6]) << 48 | static_cast<int64_t>(arr[7]) << 56;
    return (std::abs(number % (maxValue - minValue)) + minValue);
}

当我在Qt应用程序中尝试使用此代码时,我收到此错误:

terminate called after throwing an instance of 'std::runtime_error'
what():  random_device::random_device(const std::string&)

正如我之前所说的,我对C ++并不是很熟悉,但看起来我必须指定一个const std::string值。 我试过这个:

const std::string s = "s";
std::random_device rd(s);

但它会导致同样的错误。 我怎么能避免呢?

我在Windows平台上使用MinGW 4.7 32位编译器和Desktop Qt 5.0.1。 我还在.pro文件中写了QMAKE_CXXFLAGS += -std=c++0x

这是MinGW中的一个错误(在此SO回答中也有详细说明)。 基本上,MinGW没有特定于Windows的random_device实现,因此它只是尝试打开/dev/urandom ,失败并抛出std::runtime_error

VS2012的std::random_device可以直接使用mt19937或其他生成器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM