Namespaces
Variants

std::ranges:: 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
(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
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더에 정의됨 <algorithm>
호출 서명
(1) (C++20 이후)
(2) (C++20 이후)
1) 시퀀스 [ first , last ) 에서 M = min ( n, last - first ) 개의 요소를 (비복원 추출로) 선택하여, 각각의 가능한 샘플 이 동일한 확률로 나타나도록 하고, 선택된 요소들을 out 으로 시작하는 범위에 기록합니다.
알고리즘은 stable (선택된 요소들의 상대적 순서를 보존함)하며, 이는 I std:: forward_iterator 를 모델링할 때에만 해당됩니다.
동작은 다음의 경우 정의되지 않습니다: out [ first , last ) 범위 내에 있는 경우.
2) (1) 과 동일하지만, r 을 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first, last - 샘플링을 수행할 요소들의 범위 를 정의하는 반복자-감시자 쌍 ( 모집단 )
r - 샘플링을 수행할 범위 ( 모집단 )
out - 샘플들이 기록될 출력 반복자
n - 추출할 샘플의 개수
gen - 무작위성의 원천으로 사용되는 난수 생성기

반환값

결과 샘플 범위의 끝, 즉 out + M 와 동일한 반복자.

복잡도

선형 : 𝓞 ( last - first ) .

참고 사항

이 함수는 selection sampling 또는 reservoir sampling 을 구현할 수 있습니다.

가능한 구현

struct sample_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S,
             std::weakly_incrementable O, class Gen>
    requires (std::forward_iterator<I> or
              std::random_access_iterator<O>) &&
              std::indirectly_copyable<I, O> &&
              std::uniform_random_bit_generator<std::remove_reference_t<Gen>>
    O operator()(I first, S last, O out, std::iter_difference_t<I> n, Gen&& gen) const
    {
        using diff_t = std::iter_difference_t<I>;
        using distrib_t = std::uniform_int_distribution<diff_t>;
        using param_t = typename distrib_t::param_type;
        distrib_t D{};
        if constexpr (std::forward_iterator<I>)
        {
            // 이 분기는 샘플 요소들의 "안정성"을 보존합니다
            auto rest{ranges::distance(first, last)};
            for (n = ranges::min(n, rest); n != 0; ++first)
                if (D(gen, param_t(0, --rest)) < n)
                {
                    *out++ = *first;
                    --n;
                }
            return out;
        }
        else
        {
            // O는 random_access_iterator입니다
            diff_t sample_size{};
            // [first, first + M) 요소들을 "임의 접근" 출력으로 복사합니다
            for (; first != last && sample_size != n; ++first)
                out[sample_size++] = *first;
            // 복사된 요소들 중 일부를 무작위로 선택된 요소들로 덮어씁니다
            for (auto pop_size{sample_size}; first != last; ++first, ++pop_size)
            {
                const auto i{D(gen, param_t{0, pop_size})};
                if (i < n)
                    out[i] = *first;
            }
            return out + sample_size;
        }
    }
    template<ranges::input_range R, std::weakly_incrementable O, class Gen>
    requires (ranges::forward_range<R> or std::random_access_iterator<O>) &&
              std::indirectly_copyable<ranges::iterator_t<R>, O> &&
              std::uniform_random_bit_generator<std::remove_reference_t<Gen>>
    O operator()(R&& r, O out, ranges::range_difference_t<R> n, Gen&& gen) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(out), n,
                       std::forward<Gen>(gen));
    }
};
inline constexpr sample_fn sample {};

예제

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
void print(auto const& rem, auto const& v)
{
    std::cout << rem << " = [" << std::size(v) << "] { ";
    for (auto const& e : v)
        std::cout << e << ' ';
    std::cout << "}\n";
}
int main()
{
    const auto in = {1, 2, 3, 4, 5, 6};
    print("in", in);
    std::vector<int> out;
    const int max = in.size() + 2;
    auto gen = std::mt19937{std::random_device{}()};
    for (int n{}; n != max; ++n)
    {
        out.clear();
        std::ranges::sample(in, std::back_inserter(out), n, gen);
        std::cout << "n = " << n;
        print(", out", out);
    }
}

가능한 출력:

in = [6] { 1 2 3 4 5 6 }
n = 0, out = [0] { }
n = 1, out = [1] { 5 }
n = 2, out = [2] { 4 5 }
n = 3, out = [3] { 2 3 5 }
n = 4, out = [4] { 2 4 5 6 }
n = 5, out = [5] { 1 2 3 5 6 }
n = 6, out = [6] { 1 2 3 4 5 6 }
n = 7, out = [6] { 1 2 3 4 5 6 }

참고 항목

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