Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use <random> in a c++ class

Tags:

c++

random

I want to use the <random> library in my program and I will have classes with different distributions and I want to generate a number at different times in my program. Currently I have the following in my header file

    #include <random>
    #include <time.h>

    class enemy {
    private:
        int max_roll;
        typedef std::mt19937 MyRng;
        MyRng rng;

    public:
        enemy(int MR){
            max_roll = MR;
            rng.seed(time(NULL));
            std::uniform_int_distribution<int> dice(1, max_roll);
        }

        int roll() {
            return dice(rng);
        }
    };

I'm getting the issue with 'dice' being undefined even though it's in my constructor there. It will work when I move my distribution definition to the beginning of my roll function, but when I do that, I get the same number every time I call it. I've tried following the answer on this question, but I couldn't work it out.

like image 505
ShadowWesley77 Avatar asked Mar 14 '23 23:03

ShadowWesley77


1 Answers

As drescherjm pointed out, dice is a local variable within he ctor. You need to make it accessible outside the scope of the ctor.I have tried to rework your program here. I think what you want is a random number generator that generates integer values from 0 to MR ? If that is the case, you can use the reworked program below:

 #include <random>
 #include <time.h>
 #include <iostream>
    class enemy {
    private:
        std::random_device rd;
        int max_roll;
        typedef std::mt19937 MyRng;
        MyRng rng;
       std::uniform_int_distribution<int> dice;
    public:
       enemy(int MR) : max_roll(MR), rng(rd()), dice(std::uniform_int_distribution<>(1, MR)){
        rng.seed(::time(NULL));
        }

        int roll() {
            return dice(rng);
        }
    };

    int main()
    {
      enemy en(6);
      std::cout << "Roll dice produced : " << en.roll() << std::endl;
      return 0;
    }

The program is self-explanatory. Please let me know if it is not and I can take you through it.

like image 140
Faisal Avatar answered Mar 29 '23 12:03

Faisal