C ++ 0x中的随机数 [英] Random numbers in C++0x

查看:111
本文介绍了C ++ 0x中的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的C ++ 11标准有一整章专门用于随机数生成器。但是我如何执行最简单,最常见的任务,过去这样编码,但不求助于标准的C库:

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

有合理的默认值为随机数引擎,分布和种子,可以使用


b p $ p> std :: default_random_engine e((unsigned int)time(0));
int i = e();

default_random_engine 的质量取决于实现。您也可以使用 std :: min_rand0 std :: min_rand



可能一个更好的种子随机引擎的方法是使用实​​现中的随机数,而不是使用 time



Eg

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


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();

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

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.

E.g.

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

这篇关于C ++ 0x中的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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