Function object in STL

Function object:

Classes that overload function call operators are often called function object s, that is, they are objects that behave like functions. A class object, which shows the feature of a function, is defined by "object name"+( parameter list )”If there is no context, it can be treated as a function.

This is through heavy load Class.

"In the standard library, function objects are widely used to obtain elasticity". Many algorithms in the standard library can use function objects or functions as their own callback behaviors;


The corresponding code is as follows:

using namespace std;

#include "string"
#include <vector>
#include <list>
#include "set"
#include <algorithm>
#include "functional"

//Function object class overloaded ()
template<typename T>
class ShowElemt
		n = 0;

	void operator()(T &t)
		cout << t << " ";

	void printN()
		cout << " n: " << n << endl;

	int n;

//Function template = = function
template<typename T>
void FuncShowElemt(T& t)
	cout << t << endl;

//Ordinary function
void FuncShowElemt2(int& t)
	cout << t << " ";

//Definition of function object: similarities and differences between function object and common function

void main01()
	int a = 10;
	ShowElemt<int> showElemt;
	showElemt(a);   //Output 10, the execution of function object () is very similar to a function, imitated function

	FuncShowElemt<int>(a);  //Output 10
	FuncShowElemt2(a);  //Output 10

Function object belongs to class object, which can break through the concept of function and keep the call state information
 Benefits of function objects
for_each In the algorithm, the function object is the function parameter
for_each In the algorithm, when the function object returns a value

void main()
	vector<int> v1;

	for_each(v1.begin(),v1.end(),ShowElemt<int>());  // Output 1, 3, 5 / / via anonymous function object
	cout << endl;
	for_each(v1.begin(),v1.end(),FuncShowElemt2);  //Output 1, 3, 5 / / through callback function

	//The function object of the for each algorithm transfers the element value instead of the reference
	ShowElemt<int> show1;
	for_each(v1.begin(),v1.end(),show1); //Output 1, 3, 5
	show1.printN();  //Output 0

	cout<<"adopt for_each The return value of the algorithm depends on the number of calls"<<endl;
	show1 = for_each(v1.begin(), v1.end(), show1);  //Output 1, 3, 5
	show1.printN();  //Output 3

	//Key points of conclusion: it is the foundation of STL algorithm to distinguish whether the value returned by STL algorithm is iterator or predicate (function object)


275 original articles published· Getting praise 111· 250000 visitors+
Private letter follow

Added by Zwiter on Sun, 19 Apr 2020 17:47:48 +0300