sum (1) |
template <class InputIterator, class T> T accumulate (InputIterator first, InputIterator last, T init); |
---|---|
custom (2) |
template <class InputIterator, class T, class BinaryOperation> T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op); |
第二种形式:对于数列 a1,a2,a3,a4---------运用上述算法的效果为:init binary_op a1
binary_op a2 binary_op a3 binary_op
a4
#include "algostuff.hpp"
#include <iterator>#include <ostream>
#include <numeric>
using namespace std;
int main(){
vector<int> coll;
INSERT_ELEMENTS(coll,1,9);
PRINT_ELEMENTS(coll);
cout<<endl;
cout<<"sum:"<<accumulate(coll.begin(),coll.end(),0)<<endl;
cout<<"sum:"<<accumulate(coll.begin(),coll.end(),-100)<<endl;
cout<<"product:"<<accumulate(coll.begin(),coll.end(),1,multiplies<int>())<<endl;
cout<<"product:"<<accumulate(coll.begin(),coll.end(),0,multiplies<int>())<<endl;
return 0;
}
编译输出:
1 2 3 4 5 6 7 8 9
sum:45
sum:-55
product:362880
product:0