std::find_if:
在 [first,last)
查找通过pred 运算返回值为true第一个元素的迭代器.如果没有该元素,返回last
template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
上面是find_if的定义,等价于下面的函数
template<classInputIterator,classUnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while(first!=last)
{
if(pred(*first)) //这个地方是重点
return first;
++first;
}
return last;
}
例子:
// find_if example
#include <iostream>// std::cout
#include <algorithm>// std::find_if
#include <vector>// std::vector
bool IsOdd (inti)
{
return ((i % 2) == 1);
}
int main () {
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
std::cout <<"The first odd value is "<< *it <<'\n';
return0;
}
参考:
http://www.cplusplus.com/reference/algorithm/find_if/