前面我们学过查找函数find(beg,end,val),本节我们将继续学习与其功能类似的函数——find_if()函数。find_if(beg , end ,pred),它的功能是在区间[beg , end)找到第一个满足pred条件的第一个元素,并返回指向该元素的迭代器;如果没有找到这个元素,则会返回end()。
find_if(beg , end ,pred)中的"pred"读者是否理解?它指的是”谓词“,“谓词”的意思是返回值类型为bool的普通函数或仿函数。find_if()的谓词为一元谓词,“一元”指的是只有一个参数。如果读者看到某个函数的参数为“二元谓词”,则它表示的是有两个参数的返回值为bool类型的函数或仿函数,常见的二元谓词有upper_bound()和lower_bound。
比如我们需要在序列{1,3,5,6,7}中找到第一个奇数:
#include<iostream>
#include<vector>
#include<map>
#include<iterator> //使用迭代器函数进行切割,复习前面知识 next(it,n)
#include<algorithm>//包含算法头文件!
using namespace std;
/*仿函数*/
struct pred_obj
{
bool operator()(const int& a)const
{
return a%2==0;
}
} ;
/*普通函数*/
bool pred_basic(const int&a)
{
return a%2==0;
}
/*find_if(beg , end ,pred)*/
void test()
{
vector<int> v{1,3,5,6,7};
/*使用普通函数*/
auto pos1 = find_if(v.begin(),v.end(),pred_basic);
if(pos1!=v.end())
{
cout << *pos1<< '\n';
}
/*使用仿函数*/
auto pos2 = find_if(v.begin(),v.end(),pred_obj());
if(pos2!=v.end())
{
cout << *pos2<< '\n';
}
}
int main(){
system("title dotcpp.com");
test();
return 0;
}编译结果如下:

通过普通函数和仿函数我们都能找到序列中的第一个偶数6。
对于上面这个例子,我们还能换一个思路,”找到第一个非奇数的数“,此时我们可以使用find_if_not(beg, end ,pred)。该函数与find_if()使用方法相差无几,只不过概念是反过来的,需要更改查找条件,代码表达为:
#include<iostream>
#include<vector>
#include<map>
#include<iterator> //使用迭代器函数进行切割,复习前面知识 next(it,n)
#include<algorithm>//包含算法头文件!
using namespace std;
/*仿函数*/
struct pred_obj
{
bool operator()(const int& a)const
{
return a%2!=0;
}
} ;
/*普通函数*/
bool pred_basic(const int&a)
{
return a%2!=0;
}
/*find_if_not(beg , end ,pred)*/
void test()
{
vector<int> v{1,3,5,6,7};
/*使用普通函数*/
auto pos1 = find_if_not(v.begin(),v.end(),pred_basic);
if(pos1!=v.end())
{
cout << *pos1<< '\n';
}
/*使用仿函数*/
auto pos2 = find_if_not(v.begin(),v.end(),pred_obj());
if(pos2!=v.end())
{
cout << *pos2<< '\n';
}
}
int main(){
system("title dotcpp.com");
test();
return 0;
}这里更改了pred的判断条件和使用find_if_not(beg,end,pred)也能够在该序列找到6。
总结,如果我们需要按条件在区间[beg,end)内找出第一个满足pred的元素,我们就能使用find_if(beg,end,pred);同理,查找第一个不满则pred的元素,我们可以使用find_if_not(beg,end,pred)。
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程