• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function template
    <algorithm>

    std::for_each_n

    namespace std {
      template <class InputIterator, class Size, class Function>
      InputIterator
        for_each_n(InputIterator first,
                   Size n,
                   Function f);            // (1) C++17
    
      template <class InputIterator, class Size, class Function>
      constexpr InputIterator
        for_each_n(InputIterator first,
                   Size n,
                   Function f);            // (1) C++20
    
      template <class ExecutionPolicy, class ForwardIterator, class Size, class Function>
      ForwardIterator
        for_each_n(ExecutionPolicy&& exec,
                   ForwardIterator first,
                   Size n,
                   Function f);            // (2) C++17
    }
    

    概要

    イテレータ範囲[first, first + n) (範囲の先頭N要素) のすべての要素に、指定された関数を適用する。

    要件

    • FunctionMoveConstructible の要件を満たす必要があるが、CopyConstructible の要件を満たす必要はない
    • n >= 0であること

    効果

    イテレータ範囲[first, first + n) 内の全てのイテレータ if(*i) という操作を行う。

    このアルゴリズムはその他のアルゴリズムと違い、関数 f の内部で *i の値を書き換えても構わない(もちろんイテレータの型が mutable iterator の要件を満たしている場合に限る)。

    戻り値

    return first + n;
    

    備考

    • この関数は、thrust::for_each_n()を元にして並列アルゴリズムの導入に合わせて追加された。std::generate_n()std::generate()の実装を容易にするのと同様に、このアルゴリズムによってstd::for_each()の実装を簡略化できる
    • 関数 f戻り値がある場合、それは単に無視される

    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    void f(int& x)
    {
      x *= 2;
    }
    
    int main()
    {
      std::vector<int> v = {3, 1, 4, 5, 2};
    
      // コンテナvの先頭3要素に、関数f()を適用する。
      // 関数f()は要素の変更を行う
      std::for_each_n(v.begin(), 3, f);
    
      // コンテナvの先頭3要素に、ラムダ式で記述した関数オブジェクトを適用する
      std::for_each_n(v.begin(), 3, [](int x) {
        std::cout << x << std::endl;
      });
    }
    

    出力

    6
    2
    8
    

    処理系

    参照