dimanche 26 avril 2020

Random number generator global to a class

I would like to generate uniformly distributed numbers on [0,1] in C++. I know that the following code would to the job

     std::random_device  rand_dev;
     std::mt19937  generator(rand_dev());
     std::uniform_real_distribution<double>  uni(0,1);
     std::cout << uni(generator);

But my issue is that I want to generate these numbers inside a class scope. And I don't want to initalize a new random number generator everytime I call a function of this class as I will need to call this function very often. Can I somehow use the same number generator for the entire class? I tried

class test{
      private: 
        std::random_device  rand_dev;
        std::mt19937  generator(rand_dev());
        std::uniform_real_distribution<double>  uni(0,1);

      public:
        void somefunction();
  };
test::somefunction(){std::cout << uni(generator);}

But this doesn't seem to work.




Aucun commentaire:

Enregistrer un commentaire