Use std::uniform_int_distribution and define its range later

后端 未结 3 947
遇见更好的自我
遇见更好的自我 2020-12-19 18:23

I have problem where I want to create a std::uniform_int_distribution in a struct and then give its range later. Below is what I want.

#include          


        
3条回答
  •  一生所求
    2020-12-19 19:04

    Use param():

    using param_t = std::uniform_int_distribution<>::param_type;
    
    group.dis.param(param_t(0, 19));
    

    If the parameters change every time you use the distribution, then you can also consider using the two-parameter overload of operator() instead:

    std::cout << group.dis(gen, param_t(0, 19)) << ' ';
    

    As distribution objects are allowed to store extra bits of entropy obtained during a previous operator() call, this approach can be more efficient than constructing a new distribution object and assigning it.

    Note that the cppreference page is incomplete and doesn't document the requirements the standard imposes on param_type. Given a distribution type D and its associated param_type P,

    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.

    (§26.5.1.6 [rand.req.dist]/p9)

提交回复
热议问题