C ++ 0x random_device'std :: runtime_error' [英] C++0x random_device with 'std::runtime_error'
问题描述
我是一个C ++初学者,我有一个C ++ 0x随机数生成器的问题。我想使用Mersenne twister引擎来生成随机的int64_t数字,我使用之前发现的一些信息写了一个函数:
I am a C++ beginner and I have a problem with C++0x random number generator. I wanted to use Mersenne twister engine for generating random int64_t numbers, and I wrote a function using some information I've found earlier:
#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应用程序中使用这个代码时,得到这个错误:
When I'm trying to use this code in Qt application, I'm getting this error:
terminate called after throwing an instance of 'std::runtime_error'
what(): random_device::random_device(const std::string&)
熟悉C ++,但它看起来像我必须指定一个 const std :: string
值。我尝试这样:
As I said before, I'm not very familiar with C++, but it looked like I had to specify a const std::string
value. I tried this:
const std::string s = "s";
std::random_device rd(s);
但它会导致相同的错误。我如何避免它?
But it leads to the same error. How can I avoid it?
我在Windows平台上使用MinGW 4.7 32位编译器和Desktop Qt 5.0.1。我还在.pro文件中写了 QMAKE_CXXFLAGS + = -std = c ++ 0x
。
I use MinGW 4.7 32bit compiler and Desktop Qt 5.0.1 on Windows platform. I also wrote QMAKE_CXXFLAGS += -std=c++0x
in .pro file.
推荐答案
这是MinGW中的一个错误(详情请参阅此SO回答)。基本上,MinGW没有Windows特定的实现 random_device
,所以它只是试图打开 / dev / urandom
,失败,并抛出 std :: runtime_error
。
This is a bug in MinGW (also detailed in this SO answer). Basically, MinGW does not have a Windows-specific implementation of random_device
, so it just tries to open /dev/urandom
, fails, and throws std::runtime_error
.
VS2012的 std :: random_device
,直接使用 mt19937
或其他生成器即可。
VS2012's std::random_device
works, as does simply using mt19937
or another generator directly.
这篇关于C ++ 0x random_device'std :: runtime_error'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!