本文代码摘自 cplusplus.com
一,accumulate
1,调用形式:
(1)默认形式调用
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init);
(2)以指定计算方式 binary_op 调用
template <class InputIterator, class T, class BinaryOperation>
T accumulate (InputIterator first, InputIterator last, T init,BinaryOperation binary_op);
各个参数意义:
first : 参与运算的数值序列的首部
last : 参与运算的数值序列的尾部
init : 参与运算的初始值
binary_op : 计算方式
2,定义及实现:
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
while (first!=last) {
init = init + *first; // or: init=binary_op(init,*first) for the binary_op version
++first;
}
return init;
}
3,功能解释及应用:
该函数的默认功能是返回 init 与数值序列中各个元素相加后的和。
#include <iostream>
#include <functional>
#include <numeric>
using namespace std;
int myfunction (int x, int y) {
return x+2*y;} //自定义的计算方式
struct myclass {
int operator()(int x, int y) {
return x+3*y;} //重载运算符
} myobject;
int main () {
int init = 100;
int numbers[] = {
10,20,30};
cout << "使用默认方式计算: ";
cout << accumulate(numbers,numbers+3,init) << endl << endl;
cout << "使用minus函数计算: ";
cout << accumulate (numbers, numbers+3, init, std::minus<int>()) << endl << endl;
/*minus函数定义如下
template <class T> struct minus : binary_function <T,T,T> {
T operator() (const T& x, const T& y) const {return x-y;}
};
*/
cout << "使用自定义的myfunction函数计算: ";
cout << accumulate (numbers, numbers+3, init, myfunction) << endl << endl;
std::cout << "使用重载运算符计算: ";
std::cout << std::accumulate (numbers, numbers+3, init, myobject) << endl << endl;
return 0;
}