C++ Algorithm 库 - find_if() 函数
描述
C++ 函数 std::algorithm::find_if() 查找满足条件的元素的第一次出现。 它使用 一元谓词 来指定条件。
声明
以下是 std::algorithm::find_if() 函数形式 std::algorithm 头的声明。
C++98
template <class InputIterator, class UnaryPredicate> InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
参数
first − 输入迭代器到初始位置。
last − 最终位置的最终迭代器。
pred − 一元谓词,接受一个参数并返回布尔值。
返回值
返回一个迭代器,指向 (first,last) 范围内的第一个元素,其中 unary predicate 返回 true。 如果没有找到这样的元素,则函数返回 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.

