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