std::random_device not working in g++

前端 未结 1 606
野性不改
野性不改 2021-01-16 11:01

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_distributio         


        
1条回答
  •  -上瘾入骨i
    2021-01-16 11:44

    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 dist(0, words.size() - 1);
    
    for (int ii = 0; ii < 100; ++ii) {
        std::string curr = words[dist(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.

    0 讨论(0)
提交回复
热议问题