简体   繁体   中英

C++0x random_device with 'std::runtime_error'

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);
}

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&)

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?

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.

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's std::random_device works, as does simply using mt19937 or another generator directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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