On this page
std::ranges::shuffle
Defined in header <algorithm> |
||
|---|---|---|
| Call signature | ||
|
(1) | (since C++20) |
|
(2) | (since C++20) |
1) Reorders the elements in the given range
[first, last) such that each possible permutation of those elements has equal probability of appearance.
2) Same as (1), but uses
r as the range, as if using ranges::begin(r) as first and ranges::end(r) as last.
The function-like entities described on this page are niebloids, that is:
- Explicit template argument lists cannot be specified when calling any of them.
- None of them are visible to argument-dependent lookup.
- When any of them are found by normal unqualified lookup as the name to the left of the function-call operator, argument-dependent lookup is inhibited.
In practice, they may be implemented as function objects, or with special compiler extensions.
Parameters
| first, last | - | the range of elements to shuffle randomly |
| r | - | the range of elements to shuffle randomly |
| gen | - | the random number generator |
Return value
An iterator equal to last.
Complexity
Exactly (last - first) - 1 swaps.
Possible implementation
|
Example
#include <algorithm>
#include <array>
#include <iostream>
#include <random>
void print(const auto& a)
{
for (const auto e : a)
std::cout << e << ' ';
std::cout << '\n';
}
int main()
{
std::array a {'A', 'B', 'C', 'D', 'E', 'F'};
print(a);
std::random_device rd;
std::mt19937 gen {rd()};
for (int i {}; i != 3; ++i)
{
std::ranges::shuffle(a, gen);
print(a);
}
}
Possible output:
A B C D E F
F E A C D B
E C B F A D
B A E C F D
See also
|
(C++20)
|
generates the next greater lexicographic permutation of a range of elements (niebloid) |
|
(C++20)
|
generates the next smaller lexicographic permutation of a range of elements (niebloid) |
|
(until C++17)(C++11)
|
randomly re-orders elements in a range (function template) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/algorithm/ranges/shuffle