Reputation: 13303
The function std::shuffle has been introduced in C++11:
template< class RandomIt, class URNG >
void shuffle( RandomIt first, RandomIt last, URNG&& g );
and it has the same signature as one of the overloads of std::random_shuffle which was also introduced in C++11:
template< class RandomIt, class RandomFunc >
void random_shuffle( RandomIt first, RandomIt last, RandomFunc&& r );
The difference is in the third parameter where:
URNG must meet the requirements of UniformRandomNumberGenerator
Is this all? Is the difference just that shuffle
performs an extra compile time check? Is the behavior otherwise the same?
Upvotes: 24
Views: 9314
Reputation: 361312
std::random_shuffle
uses std::rand()
function to randomize the items, while the std::shuffle
uses urng
which is a better random generator, though with the particular overload of std::random_shuffle
, you can get the same behavior (as with the std::shuffle
) but that requires you to do some work to pass the third argument.
Watch this talk by Stephan T. Lavavej, in which he explains why std::rand
is a bad function and what C++ programmers should use instead:
The gist is, std::shuffle
is an improvement over std::random_shuffle
, and C++ programmers should prefer using the former.
Upvotes: 22
Reputation: 56863
If you read the documentation at cppreference.com closely, you will find that the RandomFunc
passed to random_shuffle
has a different interface. It is invoked as r(n)
. This existed before C++11.
std::shuffle
uses a standardized way of getting random numbers and invokes g()
. This standardized random number generators where introduced with C++11 together with std::shuffle
.
Upvotes: 14