std:: sample
|
定义于头文件
<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 的要求。
-
|
(until C++20) |
目录 |
参数
| first, last | - | 定义抽样元素范围(总体)的迭代器对 |
| out | - | 输出样本的输出迭代器 |
| n | - | 需要抽取的样本数量 |
| g | - | 用作随机性源的随机数生成器 |
| 类型要求 | ||
-
Distance
must be an integer type.
|
||
返回值
返回 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 个元素
(算法函数对象) |