2013-03-31 63 views
4

我是一個C++初學者,我有一個C++ 0x隨機數生成器的問題。我想用梅森捻線機引擎產生隨機數的int64_t,我使用了一些資料,我發現較早寫了一個函數:C++ 0x random_device'std :: runtime_error'

#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

+3

請每次詢問隨機數時停止創建隨機引擎。創建一個作爲對象的成員,並要求它提供一個新的隨機數。 –

回答

10

這是一個在MinGW中的錯誤(在this SO answer中也有詳細說明)。基本上,MinGW沒有Windows特定的實現random_device,所以它只是試圖打開/dev/urandom,失敗,並拋出std::runtime_error

VS2012的std::random_device的工作原理,直接使用mt19937或其他發電機。

+1

感謝您的回覆!我會盡量不使用std :: random_device。 – ahawkthomas

+0

看起來像現在它編譯但allays返回相同的數字。 http://stackoverflow.com/questions/18880654/why-do-i-get-same-sequence-for-everyrun-with-stdrandom-device-with-mingw-gcc4 – aberaud

+0

什麼是VS2012? **編輯:** Visual Studio 2012,哦,好的。那麼,我使用Code :: block,該死的... – JeromeJ