I'm trying with no luck to use the std::mt19937 generator as a class member but I always get the same result. This is an example of what I'm trying.
class Level
{
public:
Level();
private:
int generateTokenType();
std::mt19937 m_mt;
std::random_device m_randomdevice;
};
Level::Level(): m_mt(m_randomdevice())
{
}
int Level::generateTokenType()
{
std::uniform_int_distribution<int> dist(0, 10);
return dist(m_mt);
}
What I want, is to maintain the generator created and ask for numbers during program execution.
-- Edit -- Following Cornstalks answer I did that:
class Level
{
public:
Level();
private:
int generateTokenType();
std::mt19937 m_mt;
};
Level::Level(): m_mt((std::random_device())())
{
for(auto i = 0; i < 10; i++)
std::cout<<generateTokenType()<<" ";
std::cout<<std::endl;
}
int Level::generateTokenType()
{
std::uniform_int_distribution<int> dist(0, 10);
return dist(m_mt);
}
But on every execution I get the same numbers...
Move std::random_device m_randomdevice;
before std::mt19937 m_mt;
.
In C++, members are constructed/initialized in the order that they're declared in the class. Your constructor is calling m_randomdevice()
before m_randomdevice
has even been constructed.
Alternatively, get rid of the m_randomdevice
member. You could just do m_mt((std::random_device())())
to initialize m_mt
.
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