<random>

公有成员函数 (public member function)
<random>

std::uniform_int_distribution::(构造函数)

(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)
构造一个 uniform_int_distribution 对象,采用由 ab 或对象 parm 指定的分布参数。

参数

a, b
分布可以生成的值的范围的上限和下限([a,b])。
请注意,范围同时包含 ab(以及它们之间的所有整数值)。
b 应大于或等于 aa<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!


复杂度

常量。

另见