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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With