Cpp-standard-library-cpp-algorithm-for-each
提供:Dev Guides
C ++アルゴリズムライブラリ-for_each()関数
説明
- C ++関数* std
- algorithm :: for_each()*は、提供された関数を範囲の各要素に適用します。
宣言
- 以下は、std
- algorithmヘッダーからのstd :: algorithm :: for_each()関数の宣言です。
C 98
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function fn);
パラメーター
- first -イテレータを初期位置に入力します。
- last -最終位置への最終イテレータ。
- fn -範囲内の要素を引数として受け入れる単項関数。
戻り値
関数 `+ fn +`を返します。
例外
リニア。
時間の複雑さ
関数 `+ fn +`またはイテレータの操作が例外をスローした場合、例外をスローします。
無効なパラメータは未定義の動作を引き起こすことに注意してください。
例
- 次の例は、std
- algorithm :: for_each()関数の使用法を示しています。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int print_even(int n) {
if (n % 2 == 0)
cout << n << ' ';
}
int main(void) {
vector<int> v = {1, 2, 3, 4, 5};
cout << "Vector contains following even numebr" << endl;
for_each(v.begin(), v.end(), print_even);
cout << endl;
return 0;
}
上記のプログラムをコンパイルして実行すると、次の結果が生成されます-
Vector contains following even numebr
2 4