std::uniform_int_distribution
來自 cppreference.com
定義於標頭檔案 <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++11起)(C++20中移除) |
比較兩個分佈物件 (函式) |
(C++11) |
對偽隨機數分佈執行流輸入和輸出 (函式模板) |
[編輯] 示例
此程式模擬投擲六面骰子。
執行此程式碼
#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