STL中的谓词

来源:互联网 发布:fedora centos 很像吗 编辑:程序博客网 时间:2024/06/07 00:26

template<class InIt,class Pred,class Dist>

typename iterator_traits<InIt>::difference_type count_if(InIt first,InIt last,Pred pr);

在这个模板中的pr是一个谓词,那么什么叫谓词呢?


首先我们看一下和count_if同源的count(InIt  first,InIt  last,const T& val)函数,这个函数的意思呢是这样的:如果*(first+N)==val则返回true,此时执行n++,在此operator==必须是对它的操作数进行相等关系的判断。所以这个函数的返回值是与【0,last-first)的所有元素与val比较相等的元素个数!



当然有些情况下,我们要判断的逻辑不是等于而是大于,那该怎么办呢?显然上面的函数是不行的,因此聪明的设计人员便想到了另外的一种方式来表达这种功能,于是便有了count_if()的存在,而它与count()函数的区别也正是实现了这一功能的所在。在谓词pr中我们可以自己设计相应的功能,以此来完成我们想要的结果!那么自然我们就可以总结出来了,所谓的谓词的含义:用来描述或判定客体性质、特征或者客体之间关系的词项(来自百科)。说得通俗点就是:某种动作或者说操作,例如上面的“==”就是一种动作或者说操作,这也是一种谓词。而在count_if这里的谓词是广义的,它没有规定具体的动作,而是等着user去实现这种动作。


count_if()的一个实例:

#include<iostream>
#include<algorithm>
using namespace std;

bool big_0(int a){
if(a==3)
return true;
return false;
}

int main(){
int a[]={2,1,3,5,4,6,7};
cout<<count_if(a,a+6,big_0);
return 0;
}



如果使用count():

#include<iostream>
#include<algorithm>
using namespace std;


//bool big_0(int a){
// if(a==3)
// return true;
// return false;
//}


int main(){
int a[]={2,1,3,5,4,6,7};
//cout<<count_if(a,a+6,big_0);
cout<<count(a,a+6,3);


return 0;
}





0 0