什么是回调函数
函数指针主要作用其他函数的参数 这个其他函数就是<高阶函数>
作为参数的函数指针指向的函数就是所谓的回调函数 向高阶函数传递不同的函数指针
高阶函数中就调用不同的 回调函数 从而执行不同的处理功能
函数指针
函数对象
匿名函数
function和bind
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
T find_optimal(const vector<T>arr, const int n, bool(*compare)(const T&, const T&)) { //这个模板带了两个参数一个函数
T opt{ arr[0] };
for (auto i = 1; i != n; i++)
if (compare(arr[i], opt)) //arr[i] 比opt更好 arr[i] 在遍历比较
opt = arr[i];
return opt;
}
template<typename T>
using COMPARE_PTR = bool(*)(const T&, const T&);// 函数指针别名
template<typename T>
bool lesst(const T& a, const T& b) { return a < b; }
template<typename T>
bool greate(const T& a, const T& b) { return a >= b; }
template<typename T>
bool lessAbs(const T& a, const T& b) { return abs(a) < abs(b); }
int main() {
vector<double>a{ 9,-3,2,-7 };
COMPARE_PTR<double>pf = lesst; //这里也可以写成 auto pf = lesst<double> 更加简单也不需要起别名
cout << find_optimal(a, a.size(), pf) << '\t';
pf = greate;
cout<< find_optimal(a, a.size(), pf) << '\t';
pf = lessAbs;
cout << find_optimal(a, a.size(), pf) << '\t';
while (true);
return 0;
}