function template
<algorithm>
std::shuffletemplate <class RandomAccessIterator, class URNG> void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);
Randomly rearrange elements in range using generator
Rearranges the elements in the range[first,last)
randomly, using g as uniform random number generator.
The function swaps the value of each element with that of some other randomly picked element. The function determines the element picked by calling g()
.
This function works with standard generators as those defined in <random>. To shuffle the elements of the range without such a generator, see random_shuffle instead.
The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
template <class RandomAccessIterator, class URNG>
void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g)
{
for (auto i=(last-first)-1; i>0; --i) {
std::uniform_int_distribution<decltype(i)> d(0,i);
swap (first[i], first[d(g)]);
}
}
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// shuffle algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::shuffle
#include <array> // std::array
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock
int main () {
std::array<int,5> foo {1,2,3,4,5};
// obtain a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
shuffle (foo.begin(), foo.end(), std::default_random_engine(seed));
std::cout << "shuffled elements:";
for (int& x: foo) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
shuffled elements: 3 1 4 2 5
[first,last)
are modified.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4