I have used the code provided by Cornstalk in the link: How to generate a random number in C++?
It works fine if implemented within a function in my class, but I need to get random numbers in another function in that class, so the variable RNDRange (see below) must be defined at class-level. I then need to initialize it as below in function A, so I can call the variable in function B.
std::uniform_int_distribution RNDRange(0, MinimumNumberOfAnimals - 1);
With reference to the code below:
Made
std::mt19937 RandomNumberGenerator;
a class level variable and commented the same within function A. Works fine.
Tried to define RNDRange at class level so I can then initialize it in function A, and call RNDRange(RandomNumberGenerator) in function B. Since I am not able to define RNDRange at class level (don't know how) and then initialize it in function A, calling RNDRange(RandomNumberGenerator) in function B is not possible.
std::mt19937 RandomNumberGenerator; // Mersenne Twister pseudo-random generator of 32-bit numbers with a state size of 19937 bits
RandomNumberGenerator.seed(std::random_device()());
std::uniform_int_distribution<std::mt19937::result_type> RNDRange(0, MinimumNumberOfAnimals - 1); // Seeds a random number generator for the range between zero and MinimumNumberOfAnimals
double MyRnd;
for (int i = 0; i < 10; i++) // tests
{
MyRnd = RNDRange(RandomNumberGenerator);
MyRnd = MyRnd / MinimumNumberOfAnimals;
// Use MyRnd
}
Works fine within function A, but I can't understand how to define RNDRange at class level and then initialize with (0, MinimumNumberOfAnimals - 1) in function A. MinimumNumberOfAnimals is only defined in the constructor of the class.