accumulate算法


accumulate主要用于元素累加

算法模板

//accumulate.h
template <typename InputIterator, typename T>
T accumulate(InputIterator first, InputIterator last, T init) {
	for( ; first != last; ++first) {
		init = init + *first;
	}
	return init;
}

template <typename InputIterator, typename T, typename BinaryOperation>
T accumulate(InputIterator first, InputIterator last, T init, BinaryOperation binary_op) {
	for( ; first != last; ++first) {
		init = binary_op(init, *first);
	}
	return init;
}

测试程序


//main.cpp
#include <iostream>
#include "accumulate.h"
#include <vector>
#include <functional>

using namespace std;

int main(void) {
	int a[5] = {0, 1, 2, 3, 4};
	vector<int> ivec(a, a+5);

	cout << accumulate(ivec.begin(), ivec.end(), 0) << endl;				// 10
	cout << accumulate(ivec.begin(), ivec.end(), 0, minus<int>()) << endl;	       // -10
	system("pause");
	return 0;
}



你可能感兴趣的:(accumulate算法)