a.h
1 template <class T> 2 void printInterval(T first,T last) 3 { 4 for (;first!=last;first++) 5 cout<<*first<<" "; 6 } 7 8 9 int sumSquares(int total,int value) 10 { 11 return total+value*value; 12 } 13 14 15 template<typename T> 16 class sumPowers 17 { 18 private: 19 int power; 20 public: 21 sumPowers(int p):power(p){} 22 const T operator()(const T& total,const T& value) 23 { 24 T v = value; 25 for (int i=0;i<power-1;i++) 26 v = v*value; 27 return total+v; 28 } 29 };
test.cpp
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <functional> 5 #include <numeric> 6 #include "a.h" 7 8 #define SIZE 10 9 10 using namespace std; 11 12 int main() 13 { 14 15 int a[SIZE]={1,2,3,4,5,6,7,8,9,10}; 16 vector<int> v(a,a+SIZE); 17 cout<<"1) ";printInterval(v.begin(),v.end());cout<<endl; 18 19 int result = -1; 20 21 result = accumulate(v.begin(),v.end(),0); 22 cout<<"2)累加和: "<<result<<endl; 23 24 result = accumulate(v.begin(),v.end(),0,sumSquares); 25 cout<<"3)平方和:"<<result<<endl; 26 27 result = accumulate(v.begin(),v.end(),0,sumPowers<int>(3)); 28 cout<<"4)立方和: "<<result<<endl; 29 30 getchar(); 31 return 0; 32 }
numeric
1 template<class _InIt, 2 class _Ty> inline 3 _Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val) 4 { // return sum of _Val and all in [_First, _Last) 5 for (; _First != _Last; ++_First) 6 _Val = (_Ty)(_Val + *_First); 7 return (_Val); 8 } 9 10 template<class _InIt, 11 class _Ty> inline 12 _Ty accumulate(_InIt _First, _InIt _Last, _Ty _Val) 13 { // return sum of _Val and all in [_First, _Last) 14 _DEBUG_RANGE(_First, _Last); 15 return (_Accumulate(_Unchecked(_First), _Unchecked(_Last), _Val)); 16 }
1 template<class _InIt, 2 class _Ty, 3 class _Fn2> inline 4 _Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func) 5 { // return sum of _Val and all in [_First, _Last), using _Func 6 for (; _First != _Last; ++_First) 7 _Val = _Func(_Val, *_First); 8 return (_Val); 9 } 10 11 template<class _InIt, 12 class _Ty, 13 class _Fn2> inline 14 _Ty accumulate(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func) 15 { // return sum of _Val and all in [_First, _Last), using _Func 16 _DEBUG_RANGE(_First, _Last); 17 _DEBUG_POINTER(_Func); 18 return (_Accumulate(_Unchecked(_First), _Unchecked(_Last), _Val, _Func)); 19 }
若一个类重载了运算符“()”,则该类的对象就称为函数对象。