1. Definition
In STL, the function can be passed to the algorithm, or the function object can be passed to the algorithm.
So, what is a function object?
Let's take a look at its statement:
class x{public: // define function call operator return operator Const ; ...}
You can call this:
X fo;
...
Fo (arg1, arg2);
Let's look at a simple print example
PrintInt.h
#ifndef Print_int_h_#define print_int_h_<iostream>usingnamespace std; class Printint {public: voidoperator() (int Const { '; }}; #endif
FuncObjectTest.h
#ifndef Stl_alg_func_object_test_h_#defineStl_alg_func_object_test_h_#include".. /.. /testbase.h"classFuncobjecttest: Publictestbase{ Public: Funcobjecttest (Const string&c,Const string&d): Testbase (c, D) {}voidrun ();Private: voidprintfuncobject ();};#endif
FuncObjectTest.cpp
#include <vector>#include<algorithm>#include<iostream>#include"FuncObjectTest.h"#include".. /.. /core/printint.h"using namespacestd;voidfuncobjecttest::p rintfuncobject () {vector<int>Coll; //insert elements from 1 to 9 for(inti =1; I <=9; ++i) {coll.push_back (i); } //Print all elementsFor_each (Coll.cbegin (), Coll.cend (),//RangePrintint ());//Operationcout <<Endl;}voidFuncobjecttest::run () {Printstart ("Printfuncobject ()"); Printfuncobject (); Printend ("Printfuncobject ()");}
Operation Result:
----------------Printfuncobject (): Run Start----------------
1 2 3 4 5 6 7 8 9
----------------Printfuncobject (): Run End----------------
C + + 11-stl-function object (ON)