7

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

FrameBuffer
  • 757
  • 1
  • 7
  • 26
  • 3
    First, no need to be harsh. And second, I'm not getting a compiler warning. – FrameBuffer Apr 11 '15 at 17:39
  • 2
    As an advice, try enabling all warnings. For `gcc` or `clang` use `-Wall`. If you use an IDE, select an appropriate option in the project/environment setting. This should help you in the future. – milleniumbug Apr 11 '15 at 17:46

1 Answers1

11

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.

Cornstalks
  • 37,137
  • 18
  • 79
  • 144
  • Something is crazy, I did what you said but I get always the same numbers. I checked the code here [link](https://ideone.com/O7hF1u) and it works ok, but .. maybe it's something related to MinGW? – FrameBuffer Apr 11 '15 at 17:56
  • 4
    @FrameBuffer: mingw has had a broken std::random_device. Perhaps it is still broken. http://stackoverflow.com/questions/18880654/why-do-i-get-same-sequence-for-everyrun-with-stdrandom-device-with-mingw-gcc4 – Bill Lynch Apr 11 '15 at 18:22
  • 1
    Yes definitely it's broken in the version I'm using .. well, I will try to workaround that.. thank you. I will mark this answer as correct, because this mingw thing is not related to my question. – FrameBuffer Apr 11 '15 at 18:29