I'm trying to create an object that is supposed to implement some methods for my roulette program, but when compiling I got error that no member generate exist in std::random_device
here is a class example:
#include <random>
class Engine
{
public:
Engine();
int spin();
private:
std::mt19937 m_generator;
std::uniform_int_distribution<int> m_distribution;
std::random_device m_seed;
};
Engine::Engine() :
m_generator(m_seed),
m_distribution(0, 36)
{
}
int Engine::spin()
{
return m_distribution(m_generator);
}
// now let's try it out
Engine eng;
for(int i = 0; i < 20; ++i)
eng.spin();
what am I doing wrong?
the above code opens a std header with code that is not easy to understand
How to Generate Random Numbers in C++ Within a Range. Similar to 1 and 10, you can generate random numbers within any range using the modulus operator. For instance, to generate numbers between 1 and 100, you can write int random = 1+ (rand() % 100).
To initialize the random number generator call srand(time(0)); Then, to set the integer x to a value between low (inclusive) and high (exclusive): int x = int(floor(rand() / (RAND_MAX + 1.0) * (high-low) + low)); The floor() is not necessary if high and low are both non-negative.
rand() function generates random number and when you use rand()%10 , it will give you last digit of the number. Since we require random number between 1 and 10, we have used rand()%10+1 to generate random number between 1 and 10 in C++.
rand() is used to generate a series of random numbers. We use this function when we want to generate a random number in our code. Like we are making a game of ludo in C++ and we have to generate any random number between 1 and 6 so we can use rand() to generate a random number.
The engine std::mt19937
requires a seed in its constructor. You are passing it an std::random_device
. It looks like you intended to do something like
Engine::Engine() : m_generator(m_seed()), m_distribution(0, 36) {}
^^
You should also make sure m_seed
has been initialized before it is used. This will require declaring it before m_generator
:
private:
std::random_device m_seed;
std::mt19937 m_generator;
std::uniform_int_distribution<int> m_distribution;
although I suspect you don't really need that member, and you can say
Engine::Engine() : m_generator(std::random_device()()),
m_distribution(0, 36) {}
See this live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With