3.1 函数对象

在学习关联容器之前,先学习函数对象的概念

1)函数对象的概念

如果一个类将“()”运算符重载为成员函数,那么这个类就称为函数对象类,这个类的对象就是函数对象。

*例

//函数对象概念示例
#include<iostream>
using namespace std;
class CAverage{
    public:
        double operator()(int a1,int a2, int a3){
            //重载()运算符
            return (double)(a1+a2+a3)/3;//强制类型转换 
        }
};
int main(){
    CAverage average;
    cout<<average(2,3,3);  //等价于cout<<average.oprator(2,3,3); 
    return 0;
} 

“()”是目数不限的运算符,所以重载为成员函数有多少参数都可以。

2)函数对象在accumulate算法中的应用

*:

**:

//函数对象在accumulate中的应用
#include<iostream>
#include<numeric>
#include<algorithm>
#include<vector>
using namespace std;
template <class T>
void Printf(T first,T last){
    for(;first!=last;first++)
    cout<<*first<<" ";
    cout<<endl;
} 
int SumSquares(int total,int value)
{
    return total+value*value;     // 二次方 
}
template <class T>
class SumPowers
{
    private:
        int power;
    public:
        SumPowers(int p):power(p){}
        const T operator()(const T & total, const T & value)
        {
            T v=value;   //可求 power次的平方 
            for(int i=0;i<power-1;++i)
                v=v*value;
            return v+total;
        }
        
};
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<<"1)";Printf(v.begin(),v.end());
    int result=accumulate(v.begin(),v.end(),0,SumSquares);
    cout<<"2)"<<result<<endl;
    result=accumulate(v.begin(),v.end(),0,SumPowers<int>(3));//临时对象 
    cout<<"4)"<<result<<endl;
    result=accumulate(v.begin(),v.end(),0,SumPowers<int>(4));
    cout<<"5)"<<result<<endl;
    return 0;
}

 3)函数模板在sort算法上的应用

* :

sort有两个版本:

a:该模板可以用来将区间[first, last)从小到大排序。

   元素比较大小用“<"进行比较的,如果表达式”a<b“的值为true,则a排在b前面,;如果”a<b“的值为false,则相反。故被比较的对象可以用”<“比较。

template<class T>

void sort(_Randit first, RandIt last);

b:元素a b的大小通过"op(a,b)"来比较。

   op( )定义了比较大小的规则。

template<class _RandIt, class Pred>

void sort(_RandIt first, _RandIt last, Pres op);

 **:

原文地址:https://www.cnblogs.com/by-dxm/p/5463025.html