4

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.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
ahawkthomas
  • 656
  • 3
  • 13
  • 26
  • 3
    Please stop creating random engines every time you ask for a random number. Create one as a member of an object and ask it for a new random number. – Nicol Bolas Mar 31 '13 at 07:33

1 Answers1

11

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.

Community
  • 1
  • 1
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • 1
    Thanks for a reply! I will try to not use std::random_device. – ahawkthomas Mar 31 '13 at 02:30
  • Seems like now it compiles but allays returns the same numbers. http://stackoverflow.com/questions/18880654/why-do-i-get-same-sequence-for-everyrun-with-stdrandom-device-with-mingw-gcc4 – aberaud Dec 08 '14 at 20:27
  • 1
    What is VS2012? **EDIT:** Visual Studio 2012, oh ok. Well, I'm using Code::block, damn… – jeromej Jul 09 '15 at 08:12