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
?
If you are using C++11, think about using
std::shuffle
instead ofstd::random_shuffle
, and passing a random-number generator, as in the last example hererandom_shuffle
uses an implementation-defined random number generator unless you provide one. So, no, usingsrand
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.However, I recommend using the new
<random>
facilities instead of rand(). Example follows.If you really care about accuracy, quality and diversity of the ways to generate random numbers, I would highly suggest to consider using the famous
Gnu Scientific Library
(GSL)This allows real uniform generation and various algorithms for the best. See here.
Specially this and this describes the available algorithms :
EDIT : Also boost::random should be a good alternative considering the GPLness of GSL (but I never dealed with it...).