公有成员函数 (public member function)
<random>
(1) | template<class URNG>result_type operator()(URNG& g); |
---|
(2) | template<class URNG>result_type operator()(URNG& g, const param_type& parm); |
---|
生成随机数
返回一个遵循对象关联的分布参数(版本1)或由parm指定的参数(版本2)的新的随机数。
生成器对象(g)通过其operator()成员函数。离散分布对象会转换由此获取的值,以便在调用此成员函数时,使用相同的参数会产生遵循离散分布的值,并具有其可能值的适当权重。
参数
- g
- 一个均匀随机数生成器对象,用作随机性源。
URNG应为均匀随机数生成器类型,例如标准生成器类之一。
- parm
- 代表分布参数(权重)的对象,通过调用成员函数 param 获取。
param_type是一个成员类型。
返回值
A new random number. (一个新的随机数。)
result_type是一个成员类型,定义为第一个类模板参数的别名 (IntType).
示例
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 27 28 29 30 31 32 33 34
|
// discrete_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);
// in a regular die, every number is equally likely:
std::uniform_int_distribution<int> regular_die (1,6);
// in this loaded die, the 6 is three times more likely:
std::discrete_distribution<int> loaded_die {0,1,1,1,1,1,3};
int regular_score = 0;
int loaded_score = 0;
for (int i=0; i<1000; ++i) {
int regular_roll = regular_die(generator);
int loaded_roll = loaded_die(generator);
if (regular_roll<loaded_roll) ++loaded_score;
else if (regular_roll>loaded_roll) ++regular_score;
}
std::cout << "after 1000 experiments:" << std::endl;
std::cout << "regular die won: " << regular_score << " times." << std::endl;
std::cout << "loaded die won: " << loaded_score << " times." << std::endl;
std::cout << "ties: " << (1000-regular_score-loaded_score) << std::endl;
return 0;
}
|
可能的输出
after 1000 experiments:
regular die won: 299 times.
loaded die won: 540 times.
ties: 161
|