std::sample
来自 cppreference.cn
定义于头文件 <algorithm> |
||
template< class PopulationIt, class SampleIt, class Distance, class URBG > SampleIterator sample( PopulationIt first, PopulationIt last, |
(C++17 起) | |
从序列 [
first,
last)
中(不重复地)选择 n 个元素,使得每个可能的样本出现概率相等,并将这些选定的元素写入输出迭代器 out。随机数使用随机数生成器 g 生成。
如果 n 大于序列中的元素数量,则选择序列中的所有元素。
当且仅当 PopulationIt
满足 LegacyForwardIterator 的要求时,此算法是稳定的(保留选定元素的相对顺序)。
如果 first 的值类型(C++20 前)*first(C++20 起) 不可写入 out,则程序非良构。
如果满足以下任何条件,则行为是未定义的:
- out 在
[
first,
last)
范围内。 -
PopulationIt
不满足 LegacyInputIterator 的要求。 -
SampleIt
不满足 LegacyOutputIterator 的要求。 - 满足所有以下条件:
|
(直至 C++23) |
|
(C++23 起) |
-
SampleIt
不满足 LegacyRandomAccessIterator 的要求。
-
- 给定类型
T
为 std::remove_reference_t<URBG>,以下任一条件满足:
-
T
不满足 UniformRandomBitGenerator 的要求。
-
|
(C++20 前) |
目录 |
[编辑] 参数
first, last | - | 定义要从中抽样的元素 范围(总体)的迭代器对 |
out | - | 写入样本的输出迭代器 |
n | - | 要抽样的数量 |
g | - | 用作随机性来源的随机数生成器 |
类型要求 | ||
-Distance 必须是整数类型。 |
[编辑] 返回值
返回 out 在最后一个样本输出后的副本,即样本范围的末尾。
[编辑] 复杂度
与 std::distance(first, last) 呈线性关系。
[编辑] 可能的实现
参见 libstdc++、libc++ 和 MSVC STL 中的实现。
[编辑] 注意
此函数可以实现选择抽样或 水塘抽样。
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__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
[编辑] 参阅
(C++17 前)(C++11) |
随机地重排一个范围中的元素 (函数模板) |
(C++20) |
从一个序列中选择 N 个随机元素 (算法函数对象) |