CKTIS / C++
std::shuffle — randomly rearranging elements
std::shuffle rearranges a range in place using a supplied random number generator. It requires random-access iterators; a fixed seed does not guarantee the same ordering across different standard-library implementations.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
template<class RandomAccessIterator, class UniformRandomBitGenerator>
void std::shuffle(RandomAccessIterator first, RandomAccessIterator last,
UniformRandomBitGenerator&& g);std::shuffle, declared in <algorithm>, randomly rearranges the elements of the half-open range [first, last). It neither adds nor removes elements and returns void. Its contract requires equal probability for every permutation, so the result may retain the original order.
The iterators must provide random access, and the referenced elements must be swappable. Mutable std::array and std::vector are suitable examples, but std::list is not. The argument g must satisfy the uniform random bit generator requirements, as std::mt19937 from <random> does; it is not merely a seed or an arbitrary function returning numbers.
The cost is linear in the number of elements. The generator supplies randomness, and its state may change. A fixed seed helps repeat tests within the same implementation, but the standard does not prescribe a particular resulting order across standard-library implementations.
The example checks element preservation using std::is_permutation, rather than expecting a particular ordering or requiring the order to change. Consequently, its expected output is always true for a correct execution.
Examples
#include <algorithm>
#include <array>
#include <iostream>
#include <random>
int main() {
const std::array<int, 5> original{1, 2, 3, 4, 5};
auto values = original;
std::mt19937 engine{42};
std::shuffle(values.begin(), values.end(), engine);
std::cout << std::boolalpha
<< std::is_permutation(original.begin(), original.end(),
values.begin(), values.end())
<< '\n';
}
Result
true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.