公有成員函式 (public member function)
<random>
(1) | explicit uniform_int_distribution ( result_type a = 0, result_type b = numeric_limits<result_type>::max() ); |
---|
(2) | explicit uniform_int_distribution ( const param_type& parm ); |
---|
構造均勻離散分佈 (Construct uniform discrete distribution)
引數
- a, b
- 分佈可以生成的值的範圍的上限和下限([a,b])。
請注意,範圍同時包含 a 和 b(以及它們之間的所有整數值)。
b 應大於或等於 a(a<b)。
result_type是一個成員型別,表示每次呼叫 operator() 時生成的隨機數的型別。它被定義為第一個類模板引數(IntType).
- parm
- 一個表示分佈引數的物件,透過呼叫成員函式 param 獲取。
param_type是一個成員型別。
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
// uniform_int_distribution example
#include <iostream>
#include <chrono>
#include <random>
int main()
{
// construct a trivial random generator engine from a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
std::uniform_int_distribution<int> distribution(1,100);
int guess;
int number = distribution(generator);
while (true) {
std::cout << "guess the number (between 1 and 100): ";
std::cin >> guess;
if (number==guess) {std::cout << "right!\n"; break; }
else if (number>guess) std::cout << "it's greater\n";
else std::cout << "it's less\n";
}
return 0;
}
|
可能的輸出
guess the number (between 1 and 100): 50
it's greater
guess the number (between 1 and 100): 75
it's greater
guess the number (between 1 and 100): 87
it's less
guess the number (between 1 and 100): 81
it's less
guess the number (between 1 and 100): 78
it's less
guess the number (between 1 and 100): 76
right!
|