C++ 仿函数

/*******************************************************************
 * Copyright (C) stechrayo
 * Author      : stechrayo
 * Create       : 2013-4-28 10:51
 * Mail          :  stechrayo@gmail.com
 * Blog          :  http://blog.csdn.net/leiych
 *               
 * Description :  阐述C++中仿函数的基本概念            
 *               
 ******************************************************************/

#include <algorithm>
#include <list>
#include <iostream>

using namespace std;

//print为仿函数
class print{
public:
	print(void)
		:count(0)	{
	}
	void operator()(int x)
	{
		cout << x << endl;
		++count;
	}

public:
	int count;
};

int main(void)
{
	list<int> ilist;
	//初始化
	for ( size_t i = 1; i < 10; ++i)
	{
		ilist.push_back(i);
	}
	//遍历ilist元素并打印
	print p = for_each(ilist.begin(), ilist.end(), print());
	//打印ilist元素个数
	cout << p.count << endl;

	return 0;
}

下面为STL中for_echo的代码:
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));
	}


仿函数,顾名思义就是模拟函数的调用。但是在这里,其实是类重载了操作符(),然后在调用操作符的时候,会生成一个无名类,最终在内部还是通过这个无名类调用函数的。请注意上述仿函数中成员变量count=10。更多的,在《STL 源码剖析》里第1.9.2章节里说明。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值