std :: random_device在g ++中不起作用 [英] std::random_device not working in g++
问题描述
我正在Windows中将Mind与g ++一起使用来编译我的c ++代码,如下所示:
I'm using g++ with MinGW in Windows to compile my c++ code, which looks like this:
std::mt19937_64 rng(std::random_device{}());
std::uniform_int_distribution<int> dist(0, words.size() - 1);
std::string curr = words[dist(rng)];
如您所见,
这会从std :: string数组中提取一个随机单词,但是当我选择该单词时,它始终是相同的,我意识到问题出在std :: random_device上,它输出总是相同的数字.
as you can see, this extracts a random word from an array of std::string, but when I optput that word, its always the same, i've realised that the problem lies in std::random_device, which outputs always the same number.
为什么会这样?我该如何解决?
why is this happening? how can I fix it?
gcc版本5.3.0
gcc version 5.3.0
如果有帮助,我会使用vs代码进行编程
I use vs code for programming if it could help
当然我应该适当地包含随机
And of course i properly include random
推荐答案
您正在MinGW上使用std::random_device
.更具体地说,您每次需要一个随机数时都在创建一个新实例.不支持此用法(或者不会产生随机数).请参阅为什么对于MinGW具有这种行为的事实,我每次使用mingw gcc4.8.1的std :: random_device运行时都得到相同的顺序吗? >
You are using std::random_device
on MinGW. More specifically, you are creating a new instance every time you want a random number. This usage is not supported (or rather, does not produce random numbers). See Why do I get the same sequence for every run with std::random_device with mingw gcc4.8.1? for the fact that MinGW has this behavior, but to fix your particular code, you can do something like this:
std::mt19937_64 rng(std::random_device{}());
std::uniform_int_distribution<int> dist(0, words.size() - 1);
for (int ii = 0; ii < 100; ++ii) {
std::string curr = words[dist(rng)];
}
也就是说,重复使用同一random_device
,而不是一次.如果程序运行之间的随机性很重要,请考虑使用它或使用其他RNG.
That is, use the same random_device
repeatedly, rather than just once. And consider seeding it, or using a different RNG, if randomness is important between program runs.
这篇关于std :: random_device在g ++中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!