从 C++17 开始就有std::sample:
std::sample(input.begin(), input.end(), std::back_inserter(out),
n_samples, std::mt19937{std::random_device{}()});
原始答案如下。我把它留在这里供参考。
SGI's implementation of the STL 具有 random_sample 和 random_sample_n 函数:
template <class InputIterator, class RandomAccessIterator>
Random AccessIterator random_sample(InputIterator first, InputIterator last,
RandomAccessIterator ofirst,
RandomAccessIterator olast)
template <class ForwardIterator, class OutputIterator, class Distance>
OutputIterator random_sample_n(ForwardIterator first, ForwardIterator last,
OutputIterator out, Distance n)
random_sample_n 将[first, last) 范围内的元素样本随机复制到[out, out + n) 范围内。输入范围内的每个元素在输出范围内最多出现一次,样本以均匀概率选择。
很遗憾
Matt Austern 提出了几个额外的算法(大部分取自 SGI 的标准库的原始 STL 实现)。其中包括
random_sample 和 random_sample_n
(来自N3925)
但是
在 Sophia-Antipolis 会议上经过 WG21 审议后,Austern 更新了提案,产生了 [N2666]。在其他变化中,他撤回了采样算法,因为“LWG 担心它们可能对标准化的理解不够好……为 TR2 提出这些算法可能是合适的”。 LWG 随后取得了稳固的成绩
共识(10-1, 2 abs.)以支持在未来的技术报告(现在称为技术规范)中包含这些算法。
random_sample_n 算法的一个版本已进入 Library Fundamentals TS,称为 std::experimental::sample,提案的最新迭代 N3925 于 2014-02 年被采用,但仍未成为标准的一部分(可能在 C++17 中)。
除了水库采样算法,您还可以看看 Donald Knuth 在 The计算机编程艺术 - 第 2 卷 - §3.4.2。