目录
函数对象概念
概念:
- 重载函数调用操作符的类,其对象常称为函数对象
- 函数对象使用重载 () 时,行为类似函数调用,称为仿函数
本质:
- 函数对象(仿函数)是一个类,不是函数
函数对象使用
特点:
- 函数对象可以和普通函数一样的调用方式,也可以传参,可以有返回值
- 函数对象可以有自己的状态
- 函数对象可以作为参数传递
测试代码:
#include<iostream>
using namespace std;
class MyAdd {
public:
MyAdd() {
this->num = 0;
}
int operator()(int v1, int v2) {
num++;
return (v1 + v2);
}
int num;
};
void doWork(MyAdd& ma, int v1, int v2) {
cout << ma(v1, v2) << endl;;
}
void test() {
MyAdd add;
// 像普通函数那样使用
cout << add(10, 20) << endl;
cout << add(10, 20) << endl;
cout << add(10, 20) << endl;
// 更好的记录函数调用次数(自己的状态)
cout << "add 函数对象调用次数:" << add.num << endl;
// 作为参数传参
doWork(add, 10, 20);
}
int main() {
test();
system("pause");
return 0;
}
运行结果:
谓词概念
概念:
- 返回 bool 类型的仿函数称为谓词
- 如果 operator() 接受一个参数称为一元谓词
- 如果 operator() 接受两个参数称为二元谓词
一元谓词
operator() 接受一个参数
返回类型为 bool 类型的仿函数
测试代码:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
class GreaterFive {
public:
bool operator()(int value) {
return value > 5;
}
};
void test() {
vector<int>v;
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
// 查找 > 5 的数,第三个参数为谓词,传入匿名函数对象
vector<int>::iterator vit = find_if(v.begin(), v.end(), GreaterFive());
if (vit == v.end()) {
cout << "为找到" << endl;
}
else {
cout << "找到" << *vit << endl;
}
}
int main() {
test();
system("pause");
return 0;
}
find_if 算法原型
运行结果:
二元谓词
operator() 接受两个参数
仿函数返回类型为 bool 类型
测试代码:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
class MyCompare {
public:
bool operator()(int value1, int value2) {
return (value1 > value2);
}
};
void test() {
vector<int>v;
v.push_back(20);
v.push_back(50);
v.push_back(30);
v.push_back(40);
v.push_back(10);
// 排序操作
sort(v.begin(), v.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
cout << *it << " "; // 10 20 30 40 50
}
cout << endl;
// 修改排序规则,传入二元谓词,匿名函数对象
sort(v.begin(), v.end(), MyCompare());
for (vector<int>::iterator it2 = v.begin(); it2 != v.end(); ++it2) {
cout << *it2 << " "; // 50 40 30 20 10
}
cout << endl;
}
int main() {
test();
system("pause");
return 0;
}
运行结果: