I'm using the random_shuffle
on a vector like this:
#include <algorithm>
vector <Card> deck;
//some code to add cards to the deck here
random_shuffle ( deck.begin(), deck.end() );
When run, the content of the deck is mixed up, but this mixed-up order is kept when I restart the program.
Did I miss something? How can I make it truly random?
With current C++ (i.e. C++11) you can use the
shuffle
algorithm which can take a pseudo random number generator (PRNG) object (which you can seed) as third parameter:(for GCC 4.8.2 you need to compile it via
g++ -std=c++11 -Wall -g shuffle.cc -o shuffle
)In the above example, the PRNG is seeded with the current system time.
For pre-C++11 compilers you only have the
random_shuffle
algorithm in the STL - but even with that you can optionally specify a number generator object/function to it. Note that you can't just pluck in a PRNG object likemtl19937
into it (because it does not provide aoperator()(U upper_bound)
member).Thus, you can supply your own adapter like this:
You need to seed the psuedo-random number generator first using srand.
Note from link above:
Place the line:
in your code before you do anything else, such as at the start of
main()
.Without that, the default seed of 1 will always be used, leading to identical sequences from
rand()
and anything that uses it.