Dmitri Nesteruk
Dmitri Nesteruk

Reputation: 23789

Is it okay that random_shuffle uses rand()?

I want to use the random_shuffle() function from <algorithm>, but when I looked at it, it turns out it uses rand() under the covers. Is this ok for the purposes of shuffling? I was under the impression that rand() is not a very good source of random values and it's best to use something like the Mersenne Twister from <random>.

Upvotes: 2

Views: 209

Answers (1)

Cory Nelson
Cory Nelson

Reputation: 29981

The preferred method is to use std::shuffle:

std::shuffle(begin(), end(), std::mt19937());

std::random_shuffle()'s source of randomness is undefined. The Visual C++ team has commented on this, saying they're going to keep it using rand() rather than something better so that it will remain backward-compatible.

Upvotes: 3

Related Questions