一、接口实现
功能:计算区间[first,second)内所有元素和_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
for (; _First != _Last; ++_First)
_Val = _Func(_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);
return (_Accumulate(_Unchecked(_First), _Unchecked(_Last), _Val, _Func));
}
// TEMPLATE FUNCTION accumulate
template<class _InIt,
class _Ty> inline
_Ty accumulate(_InIt _First, _InIt _Last, _Ty _Val)
{ // return sum of _Val and all in [_First, _Last)
return (_STD accumulate(_First, _Last, _Val, plus<>()));
}
二、使用
#include <numeric>
#include <vector>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
vector<int> vecs{1, 2, 3, 4, 5, 6};
cout << accumulate(vecs.begin(), vecs.end(), 0) << endl;
cout << accumulate(vecs.begin(), vecs.end(), 0, minus<int>()) << endl;
return 0;
}
result: