jeudi 29 octobre 2015

random number generators from c++

I'm learning about the library, which improves on the old rand and srand in many ways. But with the rand it's clear that there is one and only one random number generator that gets called and updated whenever rand is used, wherever that is in your program. With the new way I'm not sure how to imitate this behaviour efficiently and with good style. For instance what if I want a dice roll and, aping online examples written in the main procedure, I write an object with a method like this:

class foo{
    public:
    float getDiceRoll(){
        std::random_device rd;
        std::default_random_engine e1(rd());
        std::uniform_int_distribution<int> uniform_dist(1, 6);
        return uniform_dist(e1);
   }
}

This looks terrible because the engine is re-created every time you want a dice roll. This is a bit of a contrived case, but in a large program you are going to have to put the declaration of the random number generator somewhere. As a first attempt to use I just want there to be one generator for all random numbers, like in the old days. What is the nicest way to achieve this? Easily available examples online are all written straight into the main procedure and so they do not answer this basic question. I cannot think of anything that doesn't seem like taking a sledgehammer to crack a nut. Any help would be great.




Aucun commentaire:

Enregistrer un commentaire