algorithm_sample
algorithm_sample (무작위 표본 추출)
std::sample는 소스 범위에서 서로 다른 count개의 요소를 무작위로 골라 목적지 범위에 복사해요. 각 조합이 같은 확률로 나타나요.
출처: cppreference
본문
std::sample는 소스 범위 [first, last)에서 서로 다른 count개의 요소를 무작위로 복사해서 d_first에서 시작하는 목적지 범위에 넣어요. 각 가능한 조합이 나타날 확률은 같아요. 난수의 원천은 gen이에요. <algorithm> 헤더에 정의되어 있어요. C++17부터 사용 가능해요.
template< class PopulationIt, class SampleIt, class Distance, class URBG >
SampleIterator sample( PopulationIt first, PopulationIt last,
SampleIt d_first, Distance count, URBG&& gen );
count가 std::distance(first, last)보다 크면 모든 요소가 선택돼요. gen은 UniformRandomBitGenerator여야 해요.
반환값 (Return value)
복사된 마지막 요소 다음의 반복자예요.
복잡도 (Complexity)
𝓞(N) (여기서 N = std::distance(first, last)).
예제 (Example)
#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
int main()
{
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::mt19937 gen(std::random_device{}());
std::vector<int> out;
std::sample(v.begin(), v.end(), std::back_inserter(out), 3, gen);
for (int x : out) std::cout << x << ' ';
std::cout << '\n';
}