The C++ shuffle function rearranges the elements within a specified range by placing them in random positions, employing g as a uniform random number generator.
Syntax
template <class RandomAccessIterator, class URNG>
void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);
Parameter
A random access iterator that indicates the location of the initial element within the range to be reorganized.
The final element in the range to be reorganized is indicated by a random access iterator pointing to the position immediately after it.
g : An exclusive function object referred to as a uniform random number generator.
Return value
Complexity
Complexity increases linearly within the specified range [first, last) when random values are generated and elements are swapped.
Data races
The elements within the range [first, last) undergo modifications.
Exceptions
This function will raise an exception if any errors occur during random number generation, element swapping, or iterator operations.
Please be aware that using incorrect parameters can lead to unpredictable outcomes.
Example 1
Let's explore a straightforward example to showcase the usage of the shuffle function:
#include <iostream> // std::cout
#include <algorithm> // std::shuffle
#include <array> // std::array
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock
using namespace std;
int main () {
array<int,5> foo {1,2,3,4,5};
// obtain a time-based seed:
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
shuffle (foo.begin(), foo.end(), default_random_engine(seed));
cout << "shuffled elements:";
for (int& x: foo) cout << ' ' << x;
cout << '\n';
return 0;
}
Output:
shuffled elements: 4 1 3 5 2
Example 2
Let's see another simple example:
#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
using namespace std;
int main()
{
vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
random_device rd;
mt19937 g(rd());
shuffle(v.begin(), v.end(), g);
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << "\n";
return 0;
}
Output:
8 6 10 4 2 3 7 1 9 5
Example 3
Let's see another simple example:
#include <algorithm>
#include <iostream>
#include <vector>
#include <numeric>
#include <iterator>
#include <random>
using namespace std;
int main() {
vector<int> v(10);
iota(v.begin(), v.end(), 0);
cout << "before: ";
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
random_device seed_gen;
mt19937 engine(seed_gen());
shuffle(v.begin(), v.end(), engine);
cout << " after: ";
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
Output:
before: 0 1 2 3 4 5 6 7 8 9
after: 4 3 1 2 7 0 8 9 6 5