Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between shuffle and random_shuffle c++

Tags:

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?

like image 262
Martin Drozdik Avatar asked Oct 07 '13 08:10

Martin Drozdik


People also ask

What is the use of random_shuffle?

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).

Why was std :: random_shuffle removed?

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.)

How does shuffle work in C++?

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.

What is random shuffle in C++?

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.


1 Answers

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:

  • rand() Considered Harmful

The gist is, std::shuffle is an improvement over std::random_shuffle, and C++ programmers should prefer using the former.

like image 86
Nawaz Avatar answered Sep 24 '22 03:09

Nawaz