【C++】函数对象示例2

教材P203

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

//numeric头文件中accumulate的源码:
//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;
//}

template <class T>
void PrintInterval(T first,T last)
{
    while (first != last)
    {
        cout<<*first<<" ";
        ++first;
    }
    cout<<endl;
}

double sumSquares(double init,double x)
{
    return  init + x*x;
    
}

template <class T>
class sumPowers
{
private:
    int power;
public:
    sumPowers(int p):power(p){}
    
    const T operator () (const T & init, const T & value)
    {
        T v = value;
        for (int i = 1; i < this->power; ++i) {
            v = v * value;
        }
        return init + v;
    }
};


int main(int argc, const char * argv[]) {
    int a[] = {1,2,3,4,5};
    int length = sizeof(a)/sizeof(a[0]);
    cout << "length = " <<length << endl;
    vector<int> v(a,a+length);
    
    cout << "1) ";
    PrintInterval(v.begin(),v.end());
    
    
    double acc1 = accumulate(v.begin(), v.end(), 0, sumSquares);
    cout << "2) 平方和:"<< acc1 <<endl;
    
    double acc2 = accumulate(v.begin(), v.end(), 0, sumPowers<int>(3));
    cout << "3) 立方和:"<< acc2 <<endl;
    
    double acc3 = accumulate(v.begin(), v.end(), 0, sumPowers<int>(4));
    cout << "4) 立方和:"<< acc3 <<endl;
    
    return 0;
}

 

posted @ 2022-03-15 14:29  OXYGEN1  阅读(31)  评论(0)    收藏  举报