Namespaces
Variants

std:: sample

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
sample
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
헤더 파일에 정의됨 <algorithm>
template < class PopulationIt, class SampleIt, class Distance, class URBG >

SampleIterator sample ( PopulationIt first, PopulationIt last,

SampleIt out, Distance n, URBG && g ) ;
(C++17부터)

시퀀스 [ first , last ) 에서 (복원 없이) n 개의 요소를 선택하여, 각 가능한 샘플이 동일한 확률로 나타나도록 하고, 선택된 요소들을 출력 반복자 out 에 기록합니다. 난수는 난수 생성기 g 를 사용하여 생성됩니다.

만약 n 이 시퀀스의 요소 수보다 크면, 시퀀스의 모든 요소를 선택합니다.

알고리즘은 안정적입니다(선택된 요소들의 상대적 순서를 보존함) 단, PopulationIt LegacyForwardIterator 요구 사항을 충족하는 경우에만 해당됩니다.

만약 first 의 값 타입이 (C++20 이전) * first (C++20 이후) writable 하지 않다면 out 에 대해, 프로그램은 ill-formed입니다.

다음 조건 중 하나라도 충족되면, 동작은 정의되지 않습니다:

  • out [ first , last ) 범위 내에 있습니다.
  • PopulationIt LegacyInputIterator 요구사항을 충족하지 않습니다.
  • SampleIt LegacyOutputIterator 요구사항을 충족하지 않습니다.
  • 다음 모든 조건이 충족됩니다:
(C++23 이전)
(C++23 이후)
  • T 의 반환 타입이 Distance 로 변환 가능하지 않습니다.
(C++20 이전)

목차

매개변수

first, last - 샘플링을 수행할 요소들의 범위 를 정의하는 반복자 쌍 (모집단)
out - 샘플들이 기록될 출력 반복자
n - 생성할 샘플의 개수
g - 무작위성의 원천으로 사용되는 난수 생성기
타입 요구사항
-
Distance 는 정수 타입이어야 합니다.

반환값

마지막으로 출력된 샘플 이후, 즉 샘플 범위의 끝에 있는 out 의 복사본을 반환합니다.

복잡도

선형 시간 복잡도를 가지며 std:: distance ( first, last ) 에 비례합니다.

가능한 구현

구현체는 libstdc++ , libc++ MSVC STL 에서 확인하십시오.

참고 사항

이 함수는 선택 샘플링(selection sampling) 또는 reservoir sampling 을 구현할 수 있습니다.

기능 테스트 매크로 표준 기능
__cpp_lib_sample 201603L (C++17) std::sample

예제

#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';
}

가능한 출력:

Four random letters out of ABCDEFGHIJK: EFGK

참고 항목

(until C++17) (C++11)
범위 내 요소들을 무작위로 재정렬
(함수 템플릿)
시퀀스에서 N개의 무작위 요소 선택
(알고리즘 함수 객체)