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 为起始的范围内。
该算法仅在 I 满足 std:: forward_iterator 概念时是 稳定 的(保持被选元素的相对顺序)。
out [ first , last ) 范围内,则行为未定义。
2) (1) 相同,但使用 r 作为源范围,如同使用 ranges:: begin ( r ) 作为 first ,并使用 ranges:: end ( r ) 作为 last

本页面描述的函数式实体是 算法函数对象 (非正式称为 niebloids ),即:

目录

参数

first, last - 定义从中进行抽样( 总体 )的元素范围的 迭代器-哨位对
r - 从中进行抽样的范围( 总体
out - 输出样本的输出迭代器
n - 要抽取的样本数量
gen - 用作随机性源的随机数生成器

返回值

一个等于 out + M 的迭代器,即结果采样范围的末端。

复杂度

线性 : 𝓞 ( last - first )

注释

该函数可能实现 选择抽样 蓄水池抽样

可能的实现

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 个随机元素
(函数模板)