命名空间
变体
操作

std::discrete_distribution

来自 cppreference.cn
< cpp‎ | 数值‎ | 随机
 
 
 
 
 
定义于头文件 <random>
template< class IntType = int >
class discrete_distribution;
(C++11 起)

std::discrete_distribution 在区间 [0n) 上生成随机整数,其中每个整数 i 的概率定义为 wi/S,即第 i 个整数的*权重*除以所有 n 个权重的和。

std::discrete_distribution 满足 RandomNumberDistribution 的所有要求。

目录

[编辑] 模板参数

IntType - 生成器生成的类型。如果这不是 shortintlonglong longunsigned shortunsigned intunsigned longunsigned 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++20中移除)
比较两个分布对象
(函数) [编辑]
对伪随机数分布执行流输入和输出
(函数模板) [编辑]

[编辑] 示例

#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