[英]Use std::uniform_int_distribution and define its range later
I have problem where I want to create a std::uniform_int_distribution
in a struct and then give its range later. 我在要在结构中创建
std::uniform_int_distribution
在稍后提供其范围的地方遇到问题。 Below is what I want. 以下是我想要的。
#include <random>
#include <iostream>
std::random_device rd;
std::mt19937 gen(rd());
struct group_s {
int k;
std::uniform_int_distribution<> dis;
} group;
int main()
{
group.dis(0,19);
std::cout << group.dis(gen) << ' ';
}
I am getting the following error: 我收到以下错误:
no match for call to '(std::uniform_int_distribution<>) (int, int)'
cpu_group.dis(0,19);
How do I do this? 我该怎么做呢?
Use param()
: 使用
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: 如果每次使用发行版时参数都会更改,那么您也可以考虑使用
operator()
的两参数重载来代替:
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. 由于允许分发对象存储在上一个
operator()
调用期间获得的额外的熵位,因此此方法可能比构造新的分发对象并将其分配更为有效。
Note that the cppreference page is incomplete and doesn't document the requirements the standard imposes on param_type
. 请注意,cppreference页不完整,没有记录标准对
param_type
施加的要求。 Given a distribution type D
and its associated param_type
P
, 给定分布类型
D
及其关联的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.对于
D
每个构造函数都采用与分布的参数相对应的参数,P
应当具有一个受相同要求约束的相应构造函数,并采用数量,类型和默认值相同的参数。 Moreover, for each of the member functions ofD
that return values corresponding to parameters of the distribution,P
shall have a corresponding member function with the identical name, type, and semantics.而且,对于
D
每个返回与分布参数相对应的值的成员函数,P
应当具有名称,类型和语义相同的对应成员函数。
(§26.5.1.6 [rand.req.dist]/p9) (§26.5.1.6[rand.req.dist] / p9)
You can just do 你可以做
group.dis = std::uniform_int_distribution<>(0,19);
or 要么
group.dis.param(std::uniform_int_distribution<>::param_type(0,19));
Another way would be to add a method to your struct 另一种方法是向您的结构添加方法
struct group_s {
int k;
std::uniform_int_distribution<> dis;
void set(int a, int b) { dis = std::uniform_int_distribution<>(a,b); }
} group;
group.set(0,19);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.