Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a random generator as a class member in C++11

Tags:

c++

random

c++11

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...

like image 396
FrameBuffer Avatar asked Apr 11 '15 17:04

FrameBuffer


1 Answers

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.

like image 190
Cornstalks Avatar answered Sep 20 '22 09:09

Cornstalks