仿函数(Functor)是 C++ 中一种行为类似函数的对象,它通过重载
operator()
来实现函数调用
1.基本仿函数
#include <iostream>
using namespace std;//定义仿函数
struct Add {int operator()(int a, int b) { return a + b; }
};int main()
{Add add; //创建仿函数对象cout << add(100, 101) << endl; //调用 add.operator()(100, 101)//输出:201return 0;
}
-
Add
是一个仿函数,重载了operator()
。 -
add(100, 101)
实际上调用adder.operator()(100, 101)
。
2.仿函数可以存储状态(成员变量)
#include <iostream>
using namespace std;struct Mul {int factor;Mul(int f) :factor(f) {}int operator()(int x) { return x*factor; }
};int main()
{Mul m9(9); //创建一个乘以 9 的仿函数Mul m10(10); //创建一个乘以 10 的仿函数cout << m9(2) << endl; // 2 * 9 = 19cout << m10(2) << endl; // 2 * 10 = 20;return 0;
}
-
Mul存储了一个
factor
(乘数)。 -
times9(2)
返回 9* 2
,times10(2)
返回 10* 2
3.对比普通函数
#include <iostream>
using namespace std;//普通函数
int add(int a, int b) {return a + b;
}// 仿函数
struct AddFunctor {int operator()(int a, int b) { return a + b; }
};int main() {//普通函数调用cout << add(2, 3) << endl; // 5//函数调用AddFunctor adder;cout << adder(2, 3) << endl; // 5return 0;
}
-
add(2, 3)
是普通函数调用。 -
adder(2, 3)
是仿函数调用,行为和普通函数一样。
4.仿函数用于 STL 算法
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;//仿函数:判断是否大于某个值
struct GreaterThan {int a;GreaterThan(int t) : a(t) {}bool operator()(int x) { return x > a; }
};int main() {vector<int> nums = {1, 5, 3, 7, 2, 8};//使用仿函数查找第一个大于 5 的数auto it = find_if(nums.begin(), nums.end(), GreaterThan(5));if (it != nums.end()) cout << "First number > 5: " << *it << endl; // 7return 0;
}
-
GreaterThan(5)
构造了一个仿函数,用于判断数字是否大于5
。 -
find_if
使用该仿函数查找符合条件的元素
5.仿函数作为回调
#include <string>
struct CallBack
{void operator()(const string &s) {cout << "CallBack: " << s << endl;}
};void func(const string &fs, CallBack cb) {cb("func: " + fs); //调用仿函数
}int main()
{CallBack cb;func("test", cb);//输出:CallBack: func: testreturn 0;
}
-
Callback
仿函数用于处理事件回调。 -
func调用仿函数
cb
并传递消息