Randomly shuffle C++ array (different each time)

前端 未结 1 1911
再見小時候
再見小時候 2021-01-25 15:55

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:

相关标签:
1条回答
  • 2021-01-25 16:03

    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.

    0 讨论(0)
提交回复
热议问题