std::uniform_int_distribution
定义于头文件
<random> |
||
template< class IntType = int >
class uniform_int_distribution; |
(C++11 起) | |
生成随机整数值 i ,均匀分布于闭区间 [a, b] ,即按照以下离散概率函数分布
- P(i|a,b) =
1 b − a + 1
std::uniform_int_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)(C++20 中移除)
|
比较两个分布对象 (函数) |
(C++11)
|
执行伪随机数分布的流输入和输出 (函数模板) |
示例
此程序模拟 6 面骰子。
#include <random> #include <iostream> int main() { std::random_device rd; // 将用于为随机数引擎获得种子 std::mt19937 gen(rd()); // 以播种标准 mersenne_twister_engine std::uniform_int_distribution<> dis(1, 6); for (int n=0; n<10; ++n) // 用 dis 变换 gen 所生成的随机 unsigned int 到 [1, 6] 中的 int std::cout << dis(gen) << ' '; std::cout << '\n'; }
可能的输出:
1 1 6 5 2 2 5 5 6 2