On this page
std::ranges::sample
Defined in header <algorithm> |
||
---|---|---|
Call signature | ||
|
(1) | (since C++20) |
|
(2) | (since C++20) |
1) Selects
M = min(n, last - first)
elements from the sequence [
first
,
last
)
(without replacement) such that each possible sample has equal probability of appearance, and writes those selected elements into the range beginning at out
.
The algorithm is stable (preserves the relative order of the selected elements) only if
I
models std::forward_iterator
.
The behavior is undefined if
out
is in [
first
,
last
)
.
2) Same as (1), but uses
r
as the source 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
first1, last1 | - | the range from which to make the sampling (the population) |
r | - | the range from which to make the sampling (the population) |
out | - | the output iterator where the samples are written |
n | - | number of samples to take |
gen | - | the random number generator used as the source of randomness |
Return value
An iterator equal to out + M
, that is the end of the resulting sample range.
Complexity
Linear: 𝓞(last - first)
.
Notes
This function may implement selection sampling or reservoir sampling.
Possible implementation
|
Example
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
void print(auto const& rem, auto const& v)
{
std::cout << rem << " = [" << std::size(v) << "] { ";
for (auto const& e : v)
std::cout << e << ' ';
std::cout << "}\n";
}
int main()
{
const auto in = {1, 2, 3, 4, 5, 6};
print("in", in);
std::vector<int> out;
const int max = in.size() + 2;
auto gen = std::mt19937{std::random_device{}()};
for (int n{}; n != max; ++n)
{
out.clear();
std::ranges::sample(in, std::back_inserter(out), n, gen);
std::cout << "n = " << n;
print(", out", out);
}
}
Possible output:
in = [6] { 1 2 3 4 5 6 }
n = 0, out = [0] { }
n = 1, out = [1] { 5 }
n = 2, out = [2] { 4 5 }
n = 3, out = [3] { 2 3 5 }
n = 4, out = [4] { 2 4 5 6 }
n = 5, out = [5] { 1 2 3 5 6 }
n = 6, out = [6] { 1 2 3 4 5 6 }
n = 7, out = [6] { 1 2 3 4 5 6 }
See also
(C++20)
|
randomly re-orders elements in a range (niebloid) |
(C++17)
|
selects N random elements from a sequence (function template) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/algorithm/ranges/sample