std::random_device
来自 cppreference.cn
定义于头文件 <random> |
||
class random_device; |
(C++11 起) | |
std::random_device
是一个均匀分布的整数随机数生成器,它产生非确定性随机数。
如果实现无法获得非确定性源(例如硬件设备),则 std::random_device
可以通过实现定义的伪随机数引擎来实现。在这种情况下,每个 std::random_device
对象可能生成相同的数字序列。
目录 |
[编辑] 成员类型
成员类型 | 定义 |
result_type (C++11) |
无符号 整数 |
[编辑] 成员函数
构造 | |
构造引擎 (public 成员函数) | |
operator= (已删除) (C++11) |
赋值运算符已删除 (公开成员函数) |
生成 | |
推进引擎状态并返回生成的值 (public 成员函数) | |
特性 | |
(C++11) |
获取非确定性随机数生成器的熵估计值 (public 成员函数) |
[静态] |
获取输出范围中的最小可能值 (public 静态成员函数) |
[静态] |
获取输出范围中的最大可能值 (public 静态成员函数) |
[编辑] 注意
一个值得注意的实现是旧版 MinGW-w64 中 std::random_device
是确定性的(bug 338,自 GCC 9.2 起已修复)。最新版 MinGW-w64 可从 带有 MCF 线程模型的 GCC 下载。
[编辑] 示例
运行此代码
#include <iostream> #include <map> #include <random> #include <string> int main() { std::random_device rd; std::map<int, int> hist; std::uniform_int_distribution<int> dist(0, 9); for (int n = 0; n != 20000; ++n) ++hist[dist(rd)]; // note: demo only: the performance of many // implementations of random_device degrades sharply // once the entropy pool is exhausted. For practical use // random_device is generally only used to seed // a PRNG such as mt19937 for (auto [x, y] : hist) std::cout << x << " : " << std::string(y / 100, '*') << '\n'; }
可能的输出
0 : ******************** 1 : ******************* 2 : ******************** 3 : ******************** 4 : ******************** 5 : ******************* 6 : ******************** 7 : ******************** 8 : ******************* 9 : ********************