仿函数(一)

引入:

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值