C++ Numeric Algorithms: accumulate, reduce, partial_sum & inner_product

C++ Numeric Algorithms: accumulate, reduce, partial_sum & inner_product

이 글의 핵심

Overview of numeric algorithms in C++: aggregation, parallel reduce, prefix sums, and pitfalls.

Numeric algorithms

#include <numeric>
#include <vector>

std::vector<int> v = {1, 2, 3, 4, 5};

int sum = std::accumulate(v.begin(), v.end(), 0);

int product = std::accumulate(v.begin(), v.end(), 1, std::multiplies<>());

accumulate

Sums or folds left-to-right with an optional binary op. Order is fixed — use for reproducible floating-point accumulation when order matters.

Examples

The Korean article includes: average, transform_reduce (dot product), reduce with std::execution::par, and partial_sum — code is identical; translate only cout strings mentally if you copy samples.

Numeric building blocks

std::accumulate(begin, end, init)
std::reduce(begin, end, init)

std::transform_reduce(begin1, end1, begin2, init)

std::partial_sum(begin, end, out)
std::inclusive_scan(begin, end, out)
std::exclusive_scan(begin, end, out)

std::adjacent_difference(begin, end, out)

std::inner_product(begin1, end1, begin2, init)

std::iota(begin, end, value)

Common pitfalls

  • Initial value type: match accumulator type (0LL for large sums).
  • Overflow: widen to long long or double when needed.
  • reduce vs accumulate: ordering and parallel assumptions differ.
  • Parallel execution: include <execution> and validate preconditions.

FAQ

accumulate? Sequential fold; order guaranteed.

reduce? C++17; may reorder; good with parallel policies when math allows.

transform_reduce? Map-reduce style.

Parallel? std::execution::par, par_unseq.


  • C++ Algorithm Heap
  • C++ Algorithm Count
  • C++ Algorithm Generate

Keywords

std::accumulate, std::reduce, transform_reduce, partial_sum, inner_product, iota, numeric, STL