std::experimental::sample
| Defined in header  <experimental/algorithm> | ||
| template< class PopulationIterator, class SampleIterator,           class Distance, class UniformRandomNumberGenerator > | (1) | (library fundamentals TS) | 
| template< class PopulationIterator, class SampleIterator, class Distance > SampleIterator sample( PopulationIterator first, PopulationIterator last, | (2) | (library fundamentals TS v2) | 
Selects n elements from the sequence [first; last) such that each possible sample has equal probability of appearance, and writes those selected elements into the output iterator out
If n is greater than the number of elements in the sequence, selects last-first elements.
The algorithm is stable only if PopulationIterator meets the requirements of ForwardIterator
g.| Contents | 
[edit] Parameters
| first, last | - | pair of iterators forming the range from which to make the sampling (the population) | 
| out | - | the output iterator where the samples are written. Must not be in the [first;last) range | 
| n | - | number of samples to make | 
| g | - | the random number generator used as the source of randomness | 
| - PopulationIteratormust meet the requirements ofInputIterator. | ||
| - SampleIteratormust meet the requirements ofOutputIterator. | ||
| - SampleIteratormust also meet the requirements ofRandomAccessIteratorifPopulationIteratordoesn't meetForwardIterator | ||
| - PopulationIterator's value type must be writeable toout | ||
| - Distancemust be an integer type | ||
| - UniformRandomNumberGeneratormust meet the requirements ofUniformRandomNumberGeneratorand its return type must be convertible toDistance | ||
[edit] Return value
Returns a copy of out after the last sample that was output, that is, end of the sample range.
[edit] Complexity
Linear in std::distance(first,last)
[edit] Notes
This function may implement selection sampling or reservoir sampling.
[edit] Example
#include <iostream> #include <random> #include <string> #include <iterator> #include <experimental/algorithm> int main() { std::string in = "abcdefgh", out; std::experimental::sample(in.begin(), in.end(), std::back_inserter(out), 5, std::mt19937{std::random_device{}()}); std::cout << "five random letters out of " << in << " : " << out << '\n'; }
Possible output:
five random letters out of abcdefgh : cdefg
[edit] See also
| (until C++17)(C++11) | randomly re-orders elements in a range (function template) |