std::sample
| Defined in header <algorithm>
|
||
template< class PopulationIt, class SampleIt, class Distance, class URBG >
SampleIterator sample( PopulationIt first, PopulationIt last,
SampleIt d_first, Distance count, URBG&& gen );
|
(since C++17) | |
Randomly copies count different elements from the source range [first, last) to the destination range beginning at d_first, such that each possible combination has equal probability of appearance. The source of randomness is gen.
If count is greater than std::distance(first, last), all elements in the source range will be copied.
The algorithm is stable (preserves the relative order of the selected elements) only if PopulationIt meets the requirements of LegacyForwardIterator.
If the value type of first(until C++20)*first(since C++20) is not writable to out, the program is ill-formed.
If any of the following conditions is satisfied, the behavior is undefined:
d_firstis in the source range.PopulationItdoes not meet the requirements of LegacyInputIterator.SampleItdoes not meet the requirements of LegacyOutputIterator.- All following conditions are satisfied:
|
(until C++23) |
|
(since C++23) |
SampleItdoes not meet the requirements of LegacyRandomAccessIterator.
- Given the type
Tasstd::remove_reference_t<URBG>, any of the following conditions is satisfied:
Tdoes not meet the requirements of UniformRandomBitGenerator.
|
(until C++20) |
Parameters
| first, last | - | the pair of iterators defining the source range |
| d_first | - | the beginning of the destination range |
| count | - | the sample size |
| gen | - | the random number generator |
| Type requirements | ||
-Distance must be an integer type.
| ||
Return value
The past-the-end iterator of the destination range.
Complexity
Linear in std::distance(first, last).
Notes
This function may implement selection sampling or reservoir sampling.
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_sample |
201603L |
(C++17) | std::sample
|
Possible implementation
See the implementations in libstdc++, libc++ and MSVC STL.
Example
#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
#include <string>
int main()
{
std::string in{"ABCDEFGHIJK"}, out;
std::sample(in.begin(), in.end(), std::back_inserter(out), 4,
std::mt19937{std::random_device{}()});
std::cout << "Four random letters out of " << in << ": " << out << '\n';
}
Possible output:
Four random letters out of ABCDEFGHIJK: EFGK
See also
(C++20) |
selects N random elements from a sequence (algorithm function object) |
(until C++17)(C++11) |
randomly re-orders elements in a range (function template & algorithm function object) |
(C++20) |