=====accumulate=====
Syntax:
#include
TYPE accumulate( input_iterator start, input_iterator end, TYPE val );
TYPE accumulate( input_iterator start, input_iterator end, TYPE val, BinaryFunction f );
The ''accumulate'' function computes the sum of ''val'' and all of the elements in
the range [''start'',''end'').
If the binary function ''f'' if specified, it is used instead of the ''+ operator'' to
perform the summation.
The ''accumulate'' function runs in [[/complexity|linear time]].
For example, the following code uses ''accumulate'' to sum the integers in a [[stl/vector/|vector]]:
#include
using std::cout;
#include
using std::vector;
#include
using std::accumulate;
int main() {
vector v;
const int START = 1, END = 10;
for( int i = START; i <= END; ++i ) v.push_back(i);
int sum = accumulate( v.begin(), v.end(), 0 );
cout << "sum from " << START << " to " << END << " is " << sum << '\n';
}
The ''accumulate'' function can also be used on non-numerical types. The following
example uses ''accumulate'' to concatenate all of the [[string/|strings]] in a
[[stl/vector/|vector]] into a single string:
int main () {
string str = "Hello World!";
vector vec(10,str); // vec = ["Hello World!", "Hello World!", ...]
string a = accumulate( vec.begin(), vec.end(), string("") );
cout << a << endl; // displays "Hello World!Hello World!Hello..."
}
Related Topics: [[adjacent_difference]], [[count]], [[inner_product]], [[partial_sum]]