std::random - 在 Windows 上我总是得到相同的数字

std::random - On Windows always I get the same numbers

编译后,程序总是returns相同的结果。出乎意料的是,代码在 Linux ...

上正常工作
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distribut(1, 6);

    for (int i=0; i < 10; i++)
    {
        std::cout << distribut(gen) << ' ';
    }

编译器规范:

❯ g++ --version
g++.exe (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

这里的问题是 std::random_device 对象(你用来为你的 std::mt19937 播种)可能 产生相同的种子,每次(虽然它不在我的 Windows 10 + Visual Studio 测试平台上。

来自 cppreference(加粗我的):

std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.

这是一个可能的解决方案,使用对 time(nullptr) 的 'classic' 调用作为种子,这也避免了使用 'intermediate' std::random_device 对象来生成该种子(尽管还有其他选择来获得该种子):

#include <iostream>
#include <random>
#include <ctime>

int main()
{
    std::mt19937 gen(static_cast<unsigned int>(time(nullptr)));
    std::uniform_int_distribution<> distribut(1, 6);
    for (int i = 0; i < 10; i++) {
        std::cout << distribut(gen) << ' ';
    }
    return 0;
}