#include <numeric>//accumulate need this #include <list> #include <functional> #include <iostream> using namespace std; /* * output: accumulate() operating on values {1,2,3,4} result with default addition: 10 result with minus<int> function object: -10 */ int main() { int ia[] = { 1, 2, 3, 4 }; list<int> ilist( ia, ia + 4 ); int ia_result = accumulate(&ia[0], &ia[4], 0); int ilist_res = accumulate( ilist.begin(), ilist.end(), 0, minus<int>() ); cout << "accumulate()/n/t" << "operating on values {1,2,3,4}/n/t" << "result with default addition: " << ia_result << "/n/t" << "result with minus<int> function object: " << ilist_res << endl; return 0; } /************************************************************************/ /* ① template<class _InIt, class _Ty> inline _Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val) { // return sum of _Val and all in [_First, _Last) _DEBUG_RANGE(_First, _Last); for (; _First != _Last; ++_First) _Val = _Val + *_First; return (_Val); } */ /************************************************************************/ /************************************************************************/ /* ② template<class _InIt, class _Ty, class _Fn2> inline _Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val, _Fn2 _Func) { // return sum of _Val and all in [_First, _Last), using _Func _DEBUG_RANGE(_First, _Last); _DEBUG_POINTER(_Func); for (; _First != _Last; ++_First) _Val = _Func(_Val, *_First); return (_Val); } */ /************************************************************************/ /************************************************************************/ /* ③ template<class _Ty> struct plus: public binary_function<_Ty, _Ty, _Ty> { // functor for operator+ _Ty operator()(const _Ty& _Left, const _Ty& _Right) const { // apply operator+ to operands return (_Left + _Right); } }; */ /************************************************************************/