Namespaces
Variants

std:: sample

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
sample
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
ヘッダーで定義 <algorithm>
template < class PopulationIt, class SampleIt, class Distance, class URBG >

SampleIterator sample ( PopulationIt first, PopulationIt last,

SampleIt out, Distance n, URBG && g ) ;
(C++17以降)

シーケンス n 個の要素を [ first , last ) から(非復元抽出で)選択し、可能な全ての標本が等しい確率で現れるようにし、選択された要素を出力イテレータ out に書き込みます。乱数は乱数生成器 g を使用して生成されます。

n がシーケンス内の要素数を超える場合、シーケンス内の全要素を選択します。

このアルゴリズムが安定(選択された要素の相対的な順序を保持する)であるのは、 PopulationIt LegacyForwardIterator の要件を満たす場合に限ります。

first の値型が (C++20まで) * first の値型が (C++20以降) out writable でない場合、プログラムは不適格です。

以下のいずれかの条件が満たされる場合、動作は未定義です:

  • out [ first , last ) の範囲内にあります。
  • PopulationIt LegacyInputIterator の要件を満たしていません。
  • SampleIt LegacyOutputIterator の要件を満たしていません。
  • 以下のすべての条件が満たされます:
(C++23まで)
(C++23以降)
  • T std:: remove_reference_t < URBG > として与えられた場合、以下のいずれかの条件が満たされること:
  • T の戻り値の型が Distance に変換可能でない。
(C++20以前)

目次

翻訳のポイント: - 「Contents」を「目次」に翻訳 - C++関連の専門用語(Parameters, Return value, Complexity, Possible implementation, Notes, Example, See also)は原文のまま保持 - HTMLタグ、属性、class名、IDなどは完全に保持 - 数値、リンク、構造は変更なし - プロフェッショナルな技術文書としての正確性を維持

パラメータ

first, last - サンプリングを行う要素の範囲を定義するイテレータのペア(母集団)
out - サンプルが書き込まれる出力イテレータ
n - 作成するサンプルの数
g - ランダム性のソースとして使用される乱数生成器
型要件
-
Distance は整数型でなければならない。

戻り値

最後に出力されたサンプルの後、つまりサンプル範囲の終端にある out のコピーを返します。

計算量

std:: distance ( first, last ) の要素数に対して線形。

実装例

実装は libstdc++ libc++ および MSVC STL で参照してください。

注記

この関数は選択サンプリングまたは reservoir sampling を実装する可能性があります。

機能テスト マクロ 標準 機能
__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

関連項目

(until C++17) (C++11)
範囲内の要素をランダムに並べ替える
(関数テンプレート)
シーケンスからN個のランダムな要素を選択する
(アルゴリズム関数オブジェクト)