引入:
int main(){
plus<int> pl; //仿函数+
minus<int> mu;//仿函数-
cout<<pl(10,20)<<endl;
cout<<mu(100,30)<<endl;
return 0;
}
仿函数从使用方法来看像是一个函数,但其实际是一个对象。仿函数的实现核心在于对括号的重载。
例:
using namespace std;
//仿函数 使用方法像函数 但实际是对象也叫函数对象 其核心在于括号的重载
namespace my{
template<class _Ty>
struct plus{
_Ty operator()(const _Ty& _Left,const _Ty& _Right){
return (_Left+_Right);
}
};
};
int main(){
my::plus<int> pl;
minus<int> mu;
cout<<pl(10,20)<<endl;
//等价于:
cout<<pl.operator()(10,20)<<endl;
cout<<mu(100,30)<<endl;
return 0;
}
仿函数更多情况下是为了适配算法让算法更具通用性,如:
namespace my{
template <class InputIterator, class T>
ptrdiff_t count(InputIterator first, InputIterator last, const T& value){
ptrdiff_t ret = 0;
while (first != last){
if (*first++ == value)
++ret;
}
return ret;
}
// 统计满足pred条件的元素在[first, last)中的个数
template <class InputIterator, class Predicate>
ptrdiff_t count_if(InputIterator first, InputIterator last, Predicate pred){ //pred是一个模板参数
ptrdiff_t ret = 0;
while (first != last) {
if (pred(*first++))
++ret;
}
return ret;
}
};
struct IsOdd{
bool operator()(int i){
return ((i % 2) == 1);
}
};
int main(){
// 统计10在v1中出现的次数
vector<int> v1{ 10, 20, 30, 10,30, 20, 10, 10, 20 };
cout <<my::count(v1.begin(), v1.end(), 10) << endl;
vector<int> v2{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ,13};
cout << my::count_if(v2.begin(), v2.end(), IsOdd()) << endl;//参数中有isodd函数的地址,根据pred判参数推演确定函数指针
return 0;
}