Description:
Accumulate elements within a certain period. The accumulate function calculates the sum of Val and all elements within the range of [start, end.
If binary function f is specified, it is used for computing and operations.
Syntax:
#include <NUMERIC>
T accumulate( input_iterator start, input_iterator end, T val );
T accumulate( input_iterator start, input_iterator end, T val, BinaryFunction f );
Computes the sum of the given value init and the elements in the range [first, last ). the first version uses operator + to sum up the elements, the second version uses the given binary function op.
#include <IOSTREAM>usingstd::cout;#include <VECTOR>usingstd::vector;#include <NUMERIC>usingstd::accumulate; intmain() {vector<INT> v; constintSTART = 1, END = 10;for(inti = START; i <= END; ++i ) v.push_back(i);intsum = accumulate( v.begin(), v.end(), 0 );cout <<"sum from "<< START <<" to " << END << " is "<< sum <<'\n';}
What does the third parameter mean? I think it should be an initial value. It is best to write it as (INT) 0 or double (0.0). This is also verified in C ++ primer.