c ++ - function objects

Learning resources from the summary in Chinese MOOC, North oriented programming Object Design


General definition is: if a class () member function operator overloading, the function of this class is called an object class, objects of this class is the function object.
Give an example:

#include<iostream>
using namespace std;
class average{
public:
	int operator()(int a1,int a2,int a3){return (a1 + a2 + a3)/3; } 
};
int main()
{
	average a;
	cout<< "a.operator()(2,2,2) = "<<a.operator()(2,2,2)<<endl;
	average b;
	cout<<"b(2,2,2) = "<<b(2,2,2);
	return 0;
}

The effect of the implementation of
Here Insert Picture Description
code analysis:

  1. average a;Is defined function object;
  2. a.operator()(2,2,2)The first bracket is a call to the operator of bracket, the second bracket is the transmission parameters;
  3. b(2,2,2)So that the object can be defined to call () operator; such calls, similar to an ordinary function call, so called a function object.

Compared with normal function, function object is more flexible than function, function object advantages:

  • Function objects can have their own state. We can state variables defined in the class, such a function object in a number of calls you can share this status;
  • Function object has its own unique type. We can pass the corresponding type as a parameter to instantiate the appropriate template, for example, with the function parameter arguments.

Function object instance

STL templates

template<class InIt, class T, class Pred> 
T accumulate(InIt first, InIt last, T val, Pred pr);

among them

    pr 就是个函数对象,对[first,last)中的每个迭代器 I, 执行 val = pr(val,* I) ,返回最终的val。
    Pr也可以是个函数,或者函数指针。

numeric accumulate in the header file source code is as follows:

template <class InIt, class T, class Pred>
T accumulate(InIt first, Init last, T init, Pred op)
{
    for (; first != last; ++first)
        init = op(init, *first);
    return init;
};

Where pr is the only function pointer or function object, arguments and argument when calling only the function name, the function pointer or function object. T init is the initial value, to the accumulated value, and then return to 0. Usually the initial
sample

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <numeric> 
#include <functional> 
using namespace std;
template<class T>
class sum{
public:
	T operator()(T &total,const T &value){
		total += value;
		return total;
	} 
};
int comp(int total,int value)
{
	return total + value * 4;
}
int main()
{
	const int SIZE = 10;
	int a[] = { 1,2,3,4,5,6,7,8,9,10 };
	vector<int> v(a,a + SIZE);
	int _sum = accumulate(v.begin(),v.end(),0,sum<int>());
	cout<<_sum<<endl;
	_sum = accumulate(v.begin(),v.end(),0,comp);
	cout<<_sum<<endl;
	return 0;
}

Implementation of the results
Here Insert Picture Description
of which

int _sum = accumulate(v.begin(),v.end(),0,sum<int>());

sum () argument is a function of the object, must be some brackets, indicating that the calling function object.
Instantiation

int accumulate(accumulate(vector<int>::iterator first,
vector<int>::iterator last, int init,sum<int> pr)
{
	for ( ; first != last; ++first) 
		init = op(init, *first);
	return init;
}

After instantiating the last parameter is a function object. And why do not you parentheses it? This is because the constructor assigned only once in the beginning of the call.

_sum = accumulate(v.begin(),v.end(),0,comp);

comp ie normal function calls, parentheses are not required.
Instantiated

int accumulate(accumulate(vector<int>::iterator first,
vector<int>::iterator last, int init,int (*pr)(int a,int b)){
	for ( ; first != last; ++first) 
		init = pr(init, *first);
	return init;
}

After instantiating the last parameter is a function parameter list pointer is incremented, since the type of the function name is a function pointer, thus obtained Bank will accumulate template instantiated template function as defined above;

If the object has a variable assignment required, it can be understood as the first implementation of the constructor assignment, the value is written in parentheses on the line, and then use the function object to judge evaluated.
Example:

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <numeric> 
#include <functional> 
using namespace std;
template<class T>
class sum{
	int num;
public:
	sum(int i):num(i){  }
	T operator()(T &total,const T &value){
		for(int n = 1;n <= num;n++)
			total += value;
		return total;
	} 
};
int comp(int total,int value)
{
	return total + value * 4;
}
int main()
{
	const int SIZE = 10;
	int a[] = { 1,2,3,4,5,6,7,8,9,10 };
	vector<int> v(a,a + SIZE);
	int _sum = accumulate(v.begin(),v.end(),0,sum<int>(6));
	cout<<_sum<<endl;
	_sum = accumulate(v.begin(),v.end(),0,comp);
	cout<<_sum<<endl;
	return 0;
}

Implementation of the results
Here Insert Picture Description

operator function object () member function can perform different operations depending on the internal state of the object, while the ordinary function will not be able to do this. So the function of the object is more powerful than an ordinary function.

So call the constructor function object and how to distinguish it?
Here Insert Picture Description
The class needs to Hu-defined function object to call separately.


STL's <functional> Other object templates

As the size of the relatively greater application template

  • There are two sort function list, the sort function without parameters lst2.sort();, it is arranged in the element list <ascending predetermined comparison method.
  • There is another sort function list: template void sort (T2 op) ; op can be used to compare the size, i.e. op (x, Y) x is true is considered to be the top surface.
    Here Insert Picture Description
    Which is similar to copy
template <class T1,class T2> 
void Copy(T1 s,T1 e, T2 x) {
	for(; s != e; ++s,++x) 
		*x = *s;
}

Collation

  • Returns true, means that a1 a2 must precede
  • Return false, meaning not necessarily in front of the a1 a2
  • Written collation, comparison can not cause a1, a2 true return relatively a2, a1 is also true otherwise sort would runtime error
  • Compare a1, a2 returns false comparison a2, a1 returns false, then there is no problem
#include <iostream> 
#include <iterator> 
#include<vector>
using namespace std;
class Less {
public:
	bool operator ()(int a1, int a2)
	{
		if (a1 < a2)
			return true;
		else
			return false;
	}
};
bool comp(int a1, int a2)
{
	if (a1 < a2)
		return false;
	else
		return true;
}
template<typename T,typename pr>
T _max(T* p, int n, pr _less)
{
	T temp = p[0];
	for (int i = 0; i < n; i++)
		if (_less(temp, p[i]))
			temp = p[i];
	return temp;
}
int main()
{
	int a[] = { 1,2,6,4,2,3,4,8,5 };
	cout << _max(a, 9, Less()) << endl;
	cout << _max(a, 9, comp);
	return 0;
}

Implementation of the results
Here Insert Picture Description

Published 166 original articles · won praise 45 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_44116998/article/details/104274678