Example of C + + functor application
#include <iostream>#include <list>#include <algorithm>using namespace STD;Template<classT>structgt{GT (Constt& a): M_a (a) {}BOOL operator()(Constt& left) {returnLeft >= M_a; } T m_a;};intMain () { list<int>Ilst; Ilst.push_back ( A); Ilst.push_back (178); Ilst.push_back ( $); list<int>:: Iterator iter = find_if (Ilst.begin (), Ilst.end (), gt<int> ( -));if(Ilst.end ()! = iter) {cout<<"Find"<< Endl;cout<< *iter << Endl; }Else{cout<<"not find"<< Endl; }return 0;}
Equivalence of function pointer invocation to function object invocation
#include <Windows.h>#include <iostream>#include <vector>#include <map>#include <string>#include <list>#include <algorithm>using namespace STD;//*********************************************************//function//*********************************************************BOOLGreaterThan (intLeftintright) {returnLeft >= right;}typedef BOOL(*greaterthanfuncptrtype) (int,int);//*********************************************************//Imitation function class//*********************************************************Template<classT>structgt{BOOL operator()(Constt& left,Constt& right)Const{returnLeft >= right; }};intMain () { list<int>Ilst; Ilst.push_back (Ten); Ilst.push_back ( the); Ilst.push_back ( -);//----------------------------------------------------- //called with a function pointer //-----------------------------------------------------Greaterthanfuncptrtype Pgreaterthan = GreaterThan; list<int>:: Iterator iter = Ilst.begin (); for(; ITER! = Ilst.end (); ++iter) {cout<< Pgreaterthan (*iter, -) << Endl; }//----------------------------------------------------- //Call with function object //-----------------------------------------------------gt<int> gt; iter = Ilst.begin (); for(; ITER! = Ilst.end (); ++iter) {cout<< GT (*iter, -) << Endl; }return 0;}
C++stl: Copy function