为什么每次使用 std::uniform_int_distribution 时 <random> 库都会产生相同的结果

5 c++ random compiler-errors c++11

笔记:

  1. 我的编译器是带有 c++14 语言标准的 g++ 5.1.0-2
  2. 我的 IDE 是 Code::Blocks(我也尝试过 Dev-C++ 上的代码)
  3. 我测试代码的在线 IDE 是http://cpp.sh/(C++ shell)和https://www.codechef.com/ide(CodeChef.com的 IDE),它们都运行 c++14
  4. 使用在线IDE时代码运行正常,这让我更加困惑。

这是代码:

#include <iostream>
#include <random>
#include <cstdlib>
#include <ctime>
#include <chrono>

int main() {
    srand(time(0));
    long long seed = rand();
    std::default_random_engine rand_num(seed);
    std::uniform_int_distribution<long long> range(0, 10);
    long long a = range(rand_num);
    long long b = rand_num();
    std::cout<<seed<<"\n"; // the seed is different every time (tested)
    std::cout<<a<<"\n";
    std::cout<<b<<"\n";
    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在我自己的计算机上运行代码时,带有 std::uniform_int_distribution (a) 的那个不是随机的,但可以正常工作并在在线 IDE 上创建一个随机数。

没有 std::uniform_int_distribution (b) 的那个适用于在线 IDE 和我自己的计算机。

有什么问题?我该如何解决?

更新:代码与 mt19937 引擎(std::mt19937 和 std::mt19937_64)一起工作正常

Bob*_*b__ 4

这似乎是 Windows 上 g++ 实现的一个已知问题。请参阅类似问题的已接受答案:Why do I get the sameequence for every run with std::random_device with mingw gcc4.8.1?

为了避免这个问题,您可以使用<chrono>工具来为随机数生成器提供种子:

#include <iostream>
#include <random>
#include <cstdlib>
#include <ctime>
#include <chrono>

int main() {
    srand(time(0));
    long long seed = rand();

    std::default_random_engine rand_num{static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count())};
    //                                  ^ ^ ^ ^ ^ ^^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
    std::uniform_int_distribution<long long> range{1,10};

    long long a = range(rand_num);
    long long b = rand_num();
    std::cout<<seed<<"\n"; // the seed is different every time (tested)
    std::cout<<a<<"\n";
    std::cout<<b<<"\n";
    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这在每次运行时都给了我不同的结果(在 Windows 上使用 g++)。