std::uniform_int_distribution
来自 cppreference.cn
定义于头文件 <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) |
构造新的分布 (public member function) |
(C++11) |
重置分布的内部状态 (public member function) |
生成 | |
(C++11) |
生成分布中的下一个随机数 (public member function) |
特性 | |
(C++11) |
返回分布参数 (public member function) |
(C++11) |
获取或设置分布参数对象 (public member function) |
(C++11) |
返回可能生成的最小值 (public member function) |
(C++11) |
返回可能生成的最大值 (public member function) |
[编辑] 非成员函数
(C++11)(C++11)(removed in C++20) |
比较两个分布对象 (function) |
(C++11) |
对伪随机数分布执行流输入和输出 (function template) |
[编辑] 示例
此程序模拟投掷 6 面骰子。
运行此代码
#include <iostream> #include <random> int main() { std::random_device rd; // a seed source for the random number engine std::mt19937 gen(rd()); // mersenne_twister_engine seeded with rd() std::uniform_int_distribution<> distrib(1, 6); // Use distrib to transform the random unsigned int // generated by gen into an int in [1, 6] for (int n = 0; n != 10; ++n) std::cout << distrib(gen) << ' '; std::cout << '\n'; }
可能的输出
1 1 6 5 2 2 5 5 6 2