std::sample
來自 cppreference.com
定義於標頭檔案 <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 個隨機元素 (演算法函式物件) |