Randomly shuffle C++ array (different each time)

2020-04-28 15:39发布

问题:

I want to shuffle an array in C++, and each time the program is run, I want to have a different random shuffling. I have myArray of length. Currently I am using:

random_shuffle(myArray, myArray+N)

but this produces the same shuffling every time. To include a random number, I tried:

random_shuffle(myArray, myArray+N, rand()%i)

but I get the error cannot convert parameter 3 from 'int' to 'int&'.

I considered using the shuffle function instead, based on this example, but it appears that I'm stuck using a pre-2011 compiler.

Sorry if this is an egregiously stupid question. I couldn't find anything for this particular issue on SO, and google just told me ways to create a shuffling algorithm.

回答1:

random_shuffle(myArray, myArray+N) will use std::rand() to obtain random numbers. If you want the random sequence to be different each time the program is run you need to seed the random generator first using std::srand(). It is common to seed the random number generator using the current system time, which is usually good enough for non-security-related purposes. You only need to do this once during your program's execution.

std::srand(std::time(0));

If you do not call std::srand() before the first time std::rand() is called, then std::rand() behaves as though you had called std::srand(1) -- that is, you implicitly seed it with the same value each time the program is run, which will produce the same random sequence each execution of the program.