使用Srand设置随机种子是否是现代C ++? [英] Is it modern C++ to use srand to set random seed?
问题描述
对于使用std::random_shuffle
的代码,我需要设置一个随机种子,以使所产生的伪随机序列在每次运行的程序中都不同.
For code that uses std::random_shuffle
, I need to set a random seed so that the pseudorandom sequences produced vary in each program run.
此处的代码示例呼叫
srand ( unsigned ( time (NULL) ) );
需要
#include <ctime>
#include <cstdlib>
我想知道:由于C ++ 11包括对伪随机数生成的主要更新,因此这是否仍是最新的?我应该使用什么来设置std::random_shuffle
的随机种子?
I wonder: Since C++11 includes major updates to pseudorandom number generation, is this still up to date? What should I use to set the random seed for std::random_shuffle
?
推荐答案
random_shuffle
使用实现定义的随机数生成器,除非您提供一个.因此,不,使用srand
不一定正确.
否则,它将使用您提供的生成器.如果要确保使用的是rand
,可以使用rand
.
Otherwise it uses the generator you provide. You can use rand
if you want to be sure that is what gets used.
srand(seed);
std::random_shuffle(first, last, [](int n) { return rand() % n; });
// this is a biased generator
// see <http://eternallyconfuzzled.com/arts/jsw_art_rand.aspx>
但是,我建议使用新的<random>
工具而不是rand().示例如下.
However, I recommend using the new <random>
facilities instead of rand(). Example follows.
std::default_random_engine gen(seed);
std::shuffle(first, last, gen);
这篇关于使用Srand设置随机种子是否是现代C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!