dimanche 7 avril 2019

compile time random generator

I want to write a runtime random number generator class in C++ using the random library.

#include <iostream>
#include <random>

class RandomGen {
    private:
        std::random_device _rd;
        std::mt19937 _rng;
        std::uniform_int_distribution<int> _uni_dist;
    public:
        RandomGen(int min, int max) : _rd(), _rng(_rd()), _uni_dist(min, max) {}
        int spit() { return _uni_dist(_rng);}
};

int main() {
    RandomGen rgen(0x00, 0xff);

    for (unsigned i=0; i<10; ++i) {
        std::cout << rgen.spit() << std::endl;
    }

    getchar();
    return 0;
}

I am cross compiling it in a linux-ubuntu VM for a win32 machine.

Here is the compilation command : i686-w64-mingw32-g++ -Wall -Werror -std=c++17 -m32 -s -static-libstdc++ -static-libgcc test.cpp -o test.exe

The issue is that the generator is generating the same sequence of numbers each time the program is executed, as if the numbers where already pre-determined at compile time.

How to make it generate different numbers each time executed ?




Aucun commentaire:

Enregistrer un commentaire