Learn C++
#include "stlalgorithms/alg_numeric.hpp"

Numeric Algorithms (accumulate, iota) in C++

//concept

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.

//how it works
1

accumulate reduces

std::accumulate(v.begin(), v.end(), 0) sums with + β€” pass multiplies, a lambda computes anything binary.

2

Seed type rules

The init argument sets the accumulator type: 0 means int math, 0.0 double, std::string{} concatenation.

3

iota generates sequences

std::iota(v.begin(), v.end(), 1); fills 1,2,3,... β€” instant test data and index vectors.

4

Scans and dots

partial_sum prefix-sums for running totals; inner_product dots vectors for scores and similarities.

//example
#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;
}
Output
10, 24
1accumulate with seed 0 and default + folds 1+2+3+4 = 10 as int math.
2Seed 1 with a multiply lambda folds 1*2*3*4 = 24 β€” same algorithm, custom operation.
3Both reductions print β€” sum and product from one header and two calls.
//use cases
Sums, products, and custom folds without accumulator loops
Averages via accumulate divided by size (with a double seed!)
Generating index and test sequences with iota
Dot products and running totals in numeric code

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself β€” building beats watching.