STL中的仿函数



仿函数(functor)又称之为函数对象(function object),其实就是重载了()操作符的struct,没有什么特别的地方。


STL中的部分实现


/*

template<class _InIt, class _Fn1> inline
_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{	// perform function for each element
	_DEBUG_RANGE(_First, _Last);
	_DEBUG_POINTER(_Func);
	_For_each(_Unchecked(_First), _Unchecked(_Last), _Func);

	return (_STD move(_Func));
}

template<class _InIt,class _Fn1> inline
void _For_each(_InIt _First, _InIt _Last, _Fn1& _Func)
{	// perform function for each element
	for (; _First != _Last; ++_First)
		_Func(*_First);
}

*/


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

template<class T>
class Print
{
public:
	void operator()(const T&elm)
	{
		cout << elm << ' ';
	}
};

struct Plus
{
	int operator()(const int& x, const int& y) const
	{ 
		return x + y;
	}
};


int main()
{
	int ia[] = { 0, 1, 2, 3, 4, 5 };
	int size = sizeof(ia) / sizeof(ia[0]);
	vector<int>iv(ia, ia + size);

	Print<int> obj;
	for_each(iv.begin(), iv.end(),obj);
	cout << endl;
	for_each(iv.begin(), iv.end(), Print<int>());

	int i = 123;
	Print<int>obj1;
	obj1(i);

	int a = 1, b = 2;
	Plus obj2;
	cout << obj2(a, b) << endl;


	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值