C++ 标准库 - <algorithm>

C++ std::find_if 对区间中每个元素调用谓词,返回第一个使谓词为真的迭代器。谓词常用 lambda,见Lambda 表达式。

原型

template<class InputIt, class UnaryPredicate>
InputIt find_if(InputIt first, InputIt last, UnaryPredicate p);

参数

  • first, last:搜索区间。
  • p:接受元素、返回可转换为 bool 的可调用对象。

返回值

指向首个满足条件的迭代器,或 last。

示例

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1, 3, 8, 5};
    auto it = std::find_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
    if (it != v.end()) {
        std::cout << *it << std::endl;
    }
    return 0;
}

输出:

8

注意事项

谓词不应修改被检查的元素(除非明确使用允许修改的算法)。需要最后一个满足条件的元素时,可反向迭代器配合 find_if,或自行记录。

下一页介绍count:按值计数。