find_if
在范围中找到满足指定条件的元素的第一个匹配项位置。
template<class InputIterator, class Predicate> InputIterator find_if(InputIterator first, InputIterator last, Predicate pred);
参数
first
用于确定要搜索范围中的第一个元素的位置的输入迭代器。last
用于确定要搜索范围中最后元素之后下一个元素的位置的输入迭代器。pred
用户定义的谓词函数对象或 lambda 表达式,该表达式用于定义被搜索元素满足的条件。 谓词采用单个参数并返回 true(满足条件)或 false(不满足条件)。 pred 的签名必须是有效的 bool pred(const T& arg);,其中,T 是 InputIterator 在取消引用时可隐式转换为的类型。 显示 const 关键字的目的仅为说明函数对象或 lambda 不应修改参数。
返回值
用于引用范围中满足谓词所指定条件的元素(谓词产生的结果为 true)的输入迭代器。 如果找不到满足谓词的元素,则返回 last。
备注
此模板函数是算法 find 的泛化,它将“等于指定值”谓词替换为任何谓词。 有关逻辑相反(找到不满足谓词的第一个元素),请参阅 find_if_not。
示例
// cl.exe /W4 /nologo /EHsc /MTd
#include <vector>
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
template <typename S> void print(const S& s) {
for (const auto& p : s) {
cout << "(" << p << ") ";
}
cout << endl;
}
// Test std::find()
template <class InputIterator, class T>
void find_print_result(InputIterator first, InputIterator last, const T& value) {
// call <algorithm> std::find()
auto p = find(first, last, value);
cout << "value " << value;
if (p == last) {
cout << " not found." << endl;
} else {
cout << " found." << endl;
}
}
// Test std::find_if()
template <class InputIterator, class Predicate>
void find_if_print_result(InputIterator first, InputIterator last,
Predicate Pred, const string& Str) {
// call <algorithm> std::find_if()
auto p = find_if(first, last, Pred);
if (p == last) {
cout << Str << " not found." << endl;
} else {
cout << "first " << Str << " found: " << *p << endl;
}
}
// Function to use as the UnaryPredicate argument to find_if() in this example
bool is_odd_int(int i) {
return ((i % 2) != 0);
}
int main()
{
// Test using a plain old array.
const int x[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cout << "array x[] contents: ";
print(x);
// Using non-member std::begin()/std::end() to get input iterators for the plain old array.
cout << "Test std::find() with array..." << endl;
find_print_result(begin(x), end(x), 10);
find_print_result(begin(x), end(x), 42);
cout << "Test std::find_if() with array..." << endl;
find_if_print_result(begin(x), end(x), is_odd_int, "odd integer"); // function name
find_if_print_result(begin(x), end(x), // lambda
[](int i){ return ((i % 2) == 0); }, "even integer");
// Test using a vector.
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back((i + 1) * 10);
}
cout << endl << "vector v contents: ";
print(v);
cout << "Test std::find() with vector..." << endl;
find_print_result(v.begin(), v.end(), 20);
find_print_result(v.begin(), v.end(), 12);
cout << "Test std::find_if() with vector..." << endl;
find_if_print_result(v.begin(), v.end(), is_odd_int, "odd integer");
find_if_print_result(v.begin(), v.end(), // lambda
[](int i){ return ((i % 2) == 0); }, "even integer");
}
输出
要求
标头:<algorithm>
命名空间: std