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?
The random_shuffle algorithm shuffles the elements of a sequence (first..last) in a random order. The predicate version uses the pred function to generate the indices of the elements to swap. The pred has to be a function object that takes a parameter n and returns an integral random number in the range 0 to (n - 1).
The reason for removing std::random_shuffle in C++17 is that the iterator-only version usually depends on std::rand, which is now also discussed for deprecation. (std::rand should be replaced with the classes of the <random> header, as std::rand is considered harmful.)
The shuffle() function in C++ is a function in vector library. It is a function that will rearrange the elements of any range by placing the elements at random positions. To shuffle it uses a uniform random generator which helps in shuffling the elements.
C++ Algorithm random_shuffle() reorders the elements of a range by putting them at random places. The first version uses an internal random number generator and the second version uses a random number generator which is a special kind of function object that is explicitly passed as an argument.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With