Cpp-standard-library-cpp-algorithm-find-if
提供:Dev Guides
C ++アルゴリズムライブラリ-find_if()関数
説明
- C ++関数* std
- algorithm :: find_if()*は、条件を満たす要素の最初の出現を見つけます。 条件を指定するために `+ unary predicate +`を使用します。
宣言
- 以下は、std
- algorithmヘッダーからのstd :: algorithm :: find_if()関数の宣言です。
C 98
template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last,
UnaryPredicate pred);
パラメーター
- first -イテレータを初期位置に入力します。
- last -最終位置への最終イテレータ。
- pred -1つの引数を受け入れ、boolを返す単項述語。
戻り値
`+ unary predicate `がtrueを返す範囲 `(first、last)`の最初の要素へのイテレータを返します。 そのような要素が見つからない場合、関数は ` last +`を返します。
例外
述語またはイテレータの操作が例外をスローした場合、例外をスローします。
無効なパラメータは未定義の動作を引き起こすことに注意してください。
時間の複雑さ
線形、すなわち O(n)
例
- 次の例は、std
- algorithm :: find_if()関数の使用方法を示しています。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool unary_pre(int n) {
return ((n % 2) == 0);
}
int main(void) {
vector<int> v = {10, 2, 3, 4, 5};
auto it = find_if(v.begin(), v.end(), unary_pre);
if (it != end(v))
cout << "First even number is " << *it << endl;
v = {1};
it = find_if(v.begin(), v.end(), unary_pre);
if (it == end(v))
cout << "Only odd elements present in the sequence." << endl;
return 0;
}
上記のプログラムをコンパイルして実行すると、次の結果が生成されます-
First even number is 10
Only odd elements present in the sequence.