I'm trying to shuffle array of strings and been getting the same array back after trying random_shuffle as below.
std::string arr[5] = {"a","b","c","d","e"};
random_shuffle(std::begin(arr), std::end(arr));
The shuffled array is in the same order in multiple execution of my program when I print it out.
You probably forgot to seed the random generator. This should be called at least and preferably once. Preferably at the beginning of the program.
std::srand(std::time(0));
In std::random_shuffle the random number generator is implementation-defined, but the function std::rand
is often used.
Unless you use std::srand
to seed the RNG, you will get the same shuffled order everytime you run the program.
One possible fix is to use std::srand
with std::time
as suggested by kake_fisk in this answer .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.