Vary range of uniform_int_distribution

前端 未结 3 1140
故里飘歌
故里飘歌 2020-12-01 05:20

So i have a Random object:

typedef unsigned int uint32;

class Random {
public:
    Random() = default;
    Random(std::mt19937::result_type seed) : eng(seed         


        
3条回答
  •  天涯浪人
    2020-12-01 06:01

    I'm making the DrawNumber function public for my example. You can provide an overload that takes an upper bound, and then pass a new uniform_int_distribution::param_type to uniform_int_distribution::operator()

    The param_type can be constructed using the same arguments as the corresponding distribution.

    From N3337, §26.5.1.6/9 [rand.req.dist]

    For each of the constructors of D taking arguments corresponding to parameters of the distribution, P shall have a corresponding constructor subject to the same requirements and taking arguments identical in number, type, and default values. Moreover, for each of the member functions of D that return values corresponding to parameters of the distribution, P shall have a corresponding member function with the identical name, type, and semantics.

    where D is the type of a random number distribution function object and P is the type named by D's associated param_type

    #include 
    #include 
    
    typedef unsigned int uint32;
    
    class Random {
    public:
        Random() = default;
        Random(std::mt19937::result_type seed) : eng(seed) {}
    
        uint32 DrawNumber();
        uint32 DrawNumber(uint32 ub);
    
    private:
        std::mt19937 eng{std::random_device{}()};
        std::uniform_int_distribution uniform_dist{0, UINT32_MAX};
    };
    
    uint32 Random::DrawNumber()
    {
        return uniform_dist(eng);
    }
    
    uint32 Random::DrawNumber(uint32 ub)
    {
        return uniform_dist(eng, decltype(uniform_dist)::param_type(0, ub));
    }
    
    int main()
    {
      Random r;
      std::cout << r.DrawNumber() << std::endl;
      std::cout << r.DrawNumber(42) << std::endl;
    }
    

提交回复
热议问题