From cppreference.com
template<classPopulationIt,classSampleIt,classDistance,classURBG>SampleIteratorsample(PopulationItfirst,PopulationItlast,SampleItd_first,Distancecount,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
.
If the value type of first(until C++20)*first(since C++20) is not
to out, the program is ill-formed.
If any of the following conditions is satisfied, the behavior is undefined:
d_first is in the source range.
PopulationIt does not meet the requirements of
.
SampleIt does not meet the requirements of
.
All following conditions are satisfied:
SampleIt does not meet the requirements of
.
Given the type T as std::remove_reference_t<URBG>, any of the following conditions is satisfied:
T does not meet the requirements of
.
The return type of T is not convertible to Distance.
(until C++20)Parameters
first, last - the pair of iterators defining the source
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
.
macroValueStdFeature
(C++17)std::samplePossible implementation
See the implementations in
,
and
.
Example
Run this code
#include<algorithm>#include<iostream>#include<iterator>#include<random>#include<string>intmain(){std::stringin{"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