如何使用C ++ 11标准库生成随机数 [英] How do I generate a random number using the C++11 standard library

查看:114
本文介绍了如何使用C ++ 11标准库生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的C ++ 11标准有一整章专门介绍随机数生成器.但是我如何执行以前最简单,最常见的编码,却不求助于标准C库:

The new C++11 Standard has a whole chapter dedicated to random number generators. But how do I perform the simplest, most common task that used to be coded like this, but without resorting to the standard C library:

srand((unsigned int)time(0));
int i = rand();

对于随机数引擎,发行版和种子可以直接使用的合理的默认设置吗?

Are there reasonable defaults for random-number engines, distributions, and seeds that one could use out of the box?

推荐答案

您应该可以执行以下操作:

You should be able to do something like:

std::default_random_engine e((unsigned int)time(0));
int i = e();

default_random_engine的质量取决于实现方式.您也可以使用std::min_rand0std::min_rand.

The quality of the default_random_engine is implementation dependent. You could also use std::min_rand0 or std::min_rand.

播种随机引擎的更好的方法可能是使用实现中提供的真实随机数,而不是使用time.

Probably a better way to seed a random engine is with as true a random number as is available from the implementation rather than use time.

例如

std::random_device rd;
std::default_random_engine e( rd() );

这篇关于如何使用C ++ 11标准库生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆