zoukankan      html  css  js  c++  java
  • 仿函数为何物?

    仿函数是什么

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

    如:

    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;
    	}
    

     
  • 相关阅读:
    python之函数嵌套与闭包
    python之高阶函数
    python之装饰器
    python之内置函数
    python之内置函数:map ,filter ,reduce总结
    Python之reduce函数
    install python2 python3 in same computer
    git basic
    git LF CRLF
    2 thread, first to open chat window, second to make the phone
  • 原文地址:https://www.cnblogs.com/helloweworld/p/3098899.html
Copyright © 2011-2022 走看看