函数对象
- 若一个类重载了运算符 “()” ,则该类的对象就成了函数对象
class CMyAverage
{ //函数对象类
public:
double operator()( int a1 , int a2 , int a3 )
{
return (double)( a1 + a2 + a3 ) / 3 ;
}
};
CMyAverage average; //函数对象
cout << average( 3 , 2 , 3 ); // average.operator()( 3 , 2 , 3 );
结果:
函数对象的应用示例
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <functional>
using namespace std;
int sumSquare( int total , int value )
{
return total + value * value ;
}
template < class T >
void printInterval( T first , T last )
{
//输出区间[ first , last )中的内容
for( ; first != last ; first++ )
{
cout << *first << " " ;
}
cout << endl;
}
template < class T >
class SumPower
{
private:
int power;
public:
SumPower( int p ):power( p ) {}
const T operator()( const T &total , const T &value )
{
//计算value的power次方,并加到total上
T v = value;
for( int i = 0 ; i < power - 1 ; i++)
{
v *= value;
}
return total + v ;
}
};
int main()
{
const int SIZE = 10 ;
int a1[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
vector<int> v( a1 , a1 + SIZE );
cout << "v: " << endl;
cout << printInterval( v.begin() , v.end() ) << endl;
int result = accumulate( v.begin() , v.end() , 0 , sumSquare);
cout << "平方和: " << result << endl;
result = accumulate( v.begin() , v.end() , 0 , SumPower<int>(3));
cout << "立方和: " << endl;
result = accumulate( v.begin() , v.end() , 0 , SumPower<int>(4));
cout << "4次方和: " << result <<endl;
}
结果如下: