[c++] std::sample
Syntax
Here’s the syntax for using std::sample
:
template< class PopulationIterator, class SampleIterator, class Size, class URNG >
void std::sample(PopulationIterator first, PopulationIterator last, SampleIterator out, Size n, URNG&& g);
first
,last
: The input range to sample from.out
: The output iterator to which the sample will be written.n
: The number of elements to sample.g
: The random number generator to use.
Example
Here’s an example of how you can use std::sample
to randomly sample elements from a vector:
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
int main() {
std::vector<int> population = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector<int> sample(5); // Allocate space for 5 sampled elements
std::random_device rd;
std::mt19937 g(rd());
std::sample(population.begin(), population.end(), sample.begin(), 5, g);
for (const auto& elem : sample) {
std::cout << elem << " ";
}
return 0;
}
In this example, we have a population vector containing the numbers from 1 to 10. We use std::sample
to sample 5 elements from the population and store them in the sample
vector using a random number generator g
.