C++ find_if()
C++ 算法函数find_if()
C++ 算法find_if()函数返回pred值为true的范围内的第一个元素的值,否则返回
语法
template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);
参数
first: 它指定范围的第一个元素。
last: 它指定范围的last元素。
pred : 通常是一元函数,对其范围值进行检查以返回布尔值答案。
返回值
该函数将迭代器返回到pred值为true的范围的第一个元素。如果找不到这样的元素,则该函数返回last元素。
示例1
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool isAnOdd(int i)
{
return((i%2)==1);
}
int main()
{
std::vector<int> newvector;
newvector.push_back(20);
newvector.push_back(35);
newvector.push_back(50);
newvector.push_back(65);
std::vector<int>::iterator ti = std::find_if(newvector.begin(), newvector.end(),isAnOdd);
std::cout<<"Out of the given elements, first odd element is "<<*ti<<"\n";
return 0;
}
输出:
Out of the given elements, first odd element is 35
示例2
#include<iostream>
#include<algorithm>
#include<vector>
bool isEven (int i)
{
return((i%2)==0);
}
int main()
{
std::vector<int> newvector {20, 35, 50, 65};
std::vector<int>::iterator ti;
ti= std::find_if(newvector.begin(),newvector.end(),isEven);
std::cout<<"Out of the given elements, first even element is "<<*ti<<"\n";
return 0;
}
输出:
Out of the given elements, first odd element is 20
复杂度
该函数以线性方式移动,从第一个元素开始到last元素。对于列表中的每个元素,都会检查" pred"的值。搜索继续进行,直到遇到与" pred"值不匹配的地方。
数据竞争
指定范围内的所有对象或其中一些对象都是
异常
如果任何参数抛出一个异常,该函数将引发异常。