C++11 随机数生成器

std::uniform_int_distribution

 

 

Defined in header <random>

  
template< class IntType = int >
class uniform_int_distribution;
 (since C++11)
   

Produces random integer values i, uniformly distributed on the closed interval [a, b], that is, distributed according to the discrete probability function

P(i|a,b) = 

1
b − a + 1

.

std::uniform_int_distribution satisfies all requirements of RandomNumberDistribution

Template parameters

IntType-The result type generated by the generator. The effect is undefined if this is not one of shortintlonglong longunsigned shortunsigned intunsigned long, or unsigned long long.

 

Member types

Member typeDefinition
result_typeIntType
param_typethe type of the parameter set, see RandomNumberDistribution.

Member functions

(constructor)

constructs new distribution 
(public member function)

reset

resets the internal state of the distribution 
(public member function)

Generation

operator()

generates the next random number in the distribution 
(public member function)

Characteristics

ab

returns the distribution parameters 
(public member function)

param

gets or sets the distribution parameter object 
(public member function)

min

returns the minimum potentially generated value 
(public member function)

max

returns the maximum potentially generated value 
(public member function)

Non-member functions

operator==operator!=

compares two distribution objects 
(function)

operator<<operator>>

performs stream input and output on pseudo-random number distribution 
(function template)

Example

This program simulates throwing 6-sided dice.

Run this code

#include <random>
#include <iostream>
 
int main()
{
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> dis(1, 6);
 
    for (int n=0; n<10; ++n)
        //Use dis to transform the random unsigned int generated by gen into an int in [1, 6]
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}
#include <iostream>
 
int main()
{
    std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> dis(1, 6);
 
    for (int n=0; n<10; ++n)
        //Use dis to transform the random unsigned int generated by gen into an int in [1, 6]
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

Possible output:

1 1 6 5 2 2 5 5 6 2
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值