gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:14:55 28 4
gpt4 key购买 nike

我是 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 32bit 编译器和 Desktop Qt 5.0.1。我还在 .pro 文件中写了 QMAKE_CXXFLAGS += -std=c++0x

最佳答案

这是 MinGW 中的错误(在 this SO answer 中也有详细说明)。基本上,MinGW 没有 random_device 的 Windows 特定实现,因此它只是尝试打开 /dev/urandom,失败并抛出 std::runtime_error

VS2012 的 std::random_device 可以正常工作,就像直接使用 mt19937 或其他生成器一样。

关于C++0x random_device 'std::runtime_error',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15725677/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com