c++谓词
_Pred 谓词
很多算法使用函数对象来指定要进行的二元运算,或者指定谓词来确定进行特定运算。谓词是一个返回bool类型的值的函数,因为函数对象是一种类型的对象,实现operator()()成员函数并返回bool类型的值,所以函数对象也是谓词。
谓词(返回bool类型的仿函数)
经过代码验证发现谓词不止用仿函数(函数对象)来定义,用普通函数类型定义就行,主要是返回bool类型
代码验证
#include <iostream>
#include<vector>
#include<algorithm>//算法 头文件
using namespace std;
//统计内置数据类型
//class Greater20//仿函数
//{
// public:
// bool operator()(int val){
// return val>20;
// }
//};
bool Greater20(int val){
return val>20;
}
void test01(){
vector<int>v;
v.push_back(10);
v.push_back(40);
v.push_back(30);
v.push_back(20);
v.push_back(40);
v.push_back(20);
int num=count_if(v.begin(),v.end(),Greater20);//谓词
}
int main()
{
test01();
// test02();
system("pause");
}
两种结果相同
很多算法使用函数对象来指定要进行的二元运算,或者指定谓词来确定进行特定运算。谓词是一个返回bool类型的值的函数,
因为函数对象是一种类型的对象,实现operator()()成员函数并返回bool类型的值,所以函数对象也是谓词。
所以关系应该是谓词包括普通函数和仿函数
再附带一个代码for_each的普通函数和仿函数
#include <iostream>
#include<vector>
#include<algorithm>//算法
using namespace std;
//常用遍历算法 for_each
//普通函数
void print01(int val){
cout<<val<<" ";
}
//仿函数
class print02{
public:
void operator()(int val){
cout<<val<<" ";
}
};
void test01(){
vector<int>v;
for(int i=0;i<10;i++){
v.push_back(i);
}
for_each(v.begin(),v.end(),print01);//始 末 函数名称 [这里传递的是函数指针(放函数名),不是仿函数,所以不加括号]
//创建仿函数因为重载了(),所以要加()
cout<<endl;
for_each(v.begin(),v.end(),print02());//函数对象
cout<<endl;
}
int main()
{
test01();
system("pause");
}