Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it modern C++ to use srand to set random seed?

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.

The code example here makes a call to

srand ( unsigned ( time (NULL) ) );

which needs to

#include <ctime>
#include <cstdlib>

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?

like image 749
clstaudt Avatar asked Jan 21 '13 15:01

clstaudt


2 Answers

random_shuffle uses an implementation-defined random number generator unless you provide one. So, no, using srand is not necessarily correct.

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>

However, I recommend using the new <random> facilities instead of rand(). Example follows.

std::default_random_engine gen(seed);

std::shuffle(first, last, gen);
like image 138
R. Martinho Fernandes Avatar answered Sep 22 '22 13:09

R. Martinho Fernandes


If you are using C++11, think about using std::shuffle instead of std::random_shuffle, and passing a random-number generator, as in the last example here

like image 36
rici Avatar answered Sep 24 '22 13:09

rici