[英]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.