Numeric Algorithms (accumulate, iota) in C++
The <numeric> header gathers reductions: accumulate sums a range from an initial value (with a custom binary op for products, joins, extrema), inner_product dots two ranges, iota fills 0,1,2,..., and partial_sum/scan prefix-sums. adjacent_difference inverts scans for deltas.
The initial value's type governs the whole computation β accumulate(v..., 0) sums as int (overflowing silently on big data) while accumulate(v..., 0.0) sums as double. Getting the seed type right is the entire art of correct reductions.
accumulate reduces
std::accumulate(v.begin(), v.end(), 0) sums with + β pass multiplies, a lambda computes anything binary.
Seed type rules
The init argument sets the accumulator type: 0 means int math, 0.0 double, std::string{} concatenation.
iota generates sequences
std::iota(v.begin(), v.end(), 1); fills 1,2,3,... β instant test data and index vectors.
Scans and dots
partial_sum prefix-sums for running totals; inner_product dots vectors for scores and similarities.
#include <iostream>#include <vector>#include <numeric>Β int main() { std::vector<int> v{1, 2, 3, 4}; int sum = std::accumulate(v.begin(), v.end(), 0); int prod = std::accumulate(v.begin(), v.end(), 1, [](int a, int b) { return a * b; }); std::cout << sum << ", " << prod << std::endl; return 0;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.