std::accumulate()
is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, initial value, and (by default) computes the sum of the given initial value and the elements in the given range.
The function can also be used for left folding. This is done by passing in a binary operation function object that takes the current accumulation value and the value of the current element, and returns the new accumulation value.
Take a look at the function signature of std::accumulate()
below:
std::accumulate()
#include <iostream>// The following library needs to be included to use std::accumulate()#include <numeric>#include <vector>using namespace std;int main() {std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int sum = std::accumulate(v.begin(), v.end(), 0);std::cout << sum;}
std::accumulate
with a built-in binary predicateIn the following examples, an array of integers are summed and folded:
#include <functional>#include <iostream>// The following library needs to be included to use std::accumulate()#include <numeric>#include <vector>using namespace std;int main() {std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());std::cout << product;}
std::accumulate
with a custom binary predicate#include <functional>#include <iostream>// The following library needs to be included to use std::accumulate()#include <numeric>#include <string>#include <vector>using namespace std;int main() {std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};// custom binary predicateauto dash_fold = [](std::string a, int b) {return std::move(a) + '-' + std::to_string(b);};std::string s = std::accumulate(std::next(v.begin()), v.end(),std::to_string(v[0]), // start with first elementdash_fold);std::cout << s;}