仿函数为何物?

仿函数是什么

仿函数又称函数对象,其本质是类的对象,但为什么带“函数”二字呢,因为该类重载了()运算符,使得对象使用()时类似使用函数。

如:

greater<int> ig;			
//比较大小。greater<int>是一个模板类,ig是该类的对象,这里称ig为仿函数或函数对象。
cout << ig(5, 2) << endl;	
//之所以称呼ig时带“函数”二字,是因为ig使用()操作符时类似函数调用的形式。


 

仿函数用在哪里

STL的算法一般都提供了两个版本,一个是最直观的,一个是要用户提供某种策略的,而仿函数正是为了提供策略。

如:

cout << accumulate(ivec.begin(), ivec.end(), 0) << endl;
	//15, i.e. 0 + 1 + 2 + 3 + 4 + 5
	//第一个版本,默认是元素相加。

cout << accumulate(ivec.begin(), ivec.end(), 0, minus<int>()) << endl;
	//-15, i.e. 0 - 1 - 2 - 3 - 4 - 5
	//第二个版本,minus<int>()产生了一个对象(即仿函数/函数对象)用来提供策略(这里是元素相减).

 
	//accumulate第一个版本。
	template <class InputIterator, class T>
	T accumulate(InputIterator first, InputIterator last, T init, BinaryOperation binary_op)
	{
		for ( ; first != last; ++first)
		{
			init = init + *first;
		}
		return init;
	}

	//accumulate第二个版本。
	template <class InputIterator, class T, class BinaryOperation>
	T accumulate(InputIterator first, InputIterator last, T init, BinaryOperation binary_op)
	{
		for ( ; first != last; ++first)
		{
			init = binary_op(init, *first);//binary_op不是函数,而是一个对象,它调用()操作。
		}
		return init;
	}

 
原文地址:https://www.cnblogs.com/helloweworld/p/3098899.html