std:: discrete_distribution
|
定义于头文件
<random>
|
||
|
template
<
class
IntType
=
int
>
class discrete_distribution ; |
(C++11 起) | |
std::discrete_distribution
生成区间
[
0
,
n
)
内的随机整数,其中每个独立整数
i
的概率定义为
w
i
/S
,即第
i
个整数的
权重
除以所有
n
个权重之和。
std::discrete_distribution
满足
RandomNumberDistribution
的所有要求。
目录 |
模板参数
| IntType | - | 生成器产生的结果类型。如果该类型不是 short 、 int 、 long 、 long long 、 unsigned short 、 unsigned int 、 unsigned long 或 unsigned long long 中的一种,则行为未定义。 |
成员类型
| 成员类型 | 定义 |
result_type
(C++11)
|
IntType |
param_type
(C++11)
|
参数集的类型,参见 RandomNumberDistribution 。 |
成员函数
|
(C++11)
|
构造新的分布
(公开成员函数) |
|
(C++11)
|
重置分布的内部状态
(公开成员函数) |
生成 |
|
|
(C++11)
|
生成分布中的下一个随机数
(公开成员函数) |
特性 |
|
|
获取概率列表
(公开成员函数) |
|
|
(C++11)
|
获取或设置分布参数对象
(公开成员函数) |
|
(C++11)
|
返回可能生成的最小值
(公开成员函数) |
|
(C++11)
|
返回可能生成的最大值
(公开成员函数) |
非成员函数
|
(C++11)
(C++11)
(removed in C++20)
|
比较两个分布对象
(函数) |
|
(C++11)
|
对伪随机数分布执行流输入和输出操作
(函数模板) |
示例
#include <iomanip> #include <iostream> #include <map> #include <random> int main() { std::random_device rd; std::mt19937 gen(rd()); std::discrete_distribution<> d({40, 10, 10, 40}); std::map<int, int> map; for (int n = 0; n < 1e4; ++n) ++map[d(gen)]; for (const auto& [num, count] : map) std::cout << num << " generated " << std::setw(4) << count << " times\n"; }
可能的输出:
0 generated 4037 times 1 generated 962 times 2 generated 1030 times 3 generated 3971 times