名稱空間
變體
操作

std::random_device

來自 cppreference.com
< cpp‎ | 數值‎ | 隨機
 
 
 
 
 
定義於標頭檔案 <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 : ********************