使自己的随机数类与uniform_int_distribution相兼容

时间:2016-09-21 11:57:42

标签: c++ c++11 random

我创建了一个实现MersenneTwister算法的类来生成伪随机数。我的问题是如何让我的生成器使用默认的std :: uniform_int_distribution?我班的标题如下:

class MersenneTwister
{
public:
    void initialize(unsigned int seed);
    unsigned int extract();

private:
    unsigned int twist();
    unsigned int _x[624];
    signed int _index;
};

1 个答案:

答案 0 :(得分:6)

对UniformRandomBitGenerator概念进行建模应该这样做:

http://en.cppreference.com/w/cpp/concept/UniformRandomBitGenerator

Screenshot of the concept's requirements

这样的事情:

#include <limits>

class MersenneTwister
{
public:
    void initialize(unsigned int seed);
    unsigned int extract();

    //
    // model the concept here
    //

    using result_type = unsigned int;
    static constexpr result_type min() { return std::numeric_limits<result_type>::min(); }
    static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }
    result_type operator()()
    {
        return extract();
    }

private:
    unsigned int twist();
    unsigned int _x[624];
    signed int _index;
};