Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::inner_product: ordered dot-product fold

std::inner_product combines pairs from two ranges, folds them from init in order, and returns the accumulator.

Version: C++23

Syntax

template<class InputIt1, class InputIt2, class T>
constexpr T std::inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init);

template<class InputIt1, class InputIt2, class T, class BinaryOp1, class BinaryOp2>
constexpr T std::inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryOp1 reduce, BinaryOp2 transform);

The four-argument std::inner_product performs acc = std::move(acc) + (*i1) * (*i2) for each pair. The six-argument form replaces multiplication with binary_op2 and addition with binary_op1. [first1,last1) determines the count; the second range must provide at least that many accessible elements.

The example multiplies 1*4, 2*5, and 3*6, then adds them in order to init == 10, producing 42. Unlike std::transform_reduce, this algorithm preserves order and therefore also supports meaningful noncommutative operations.

T must be copy-constructible and copy-assignable, and the operations must neither modify elements nor invalidate iterators or subranges. Since C++20 the accumulator is passed to reduction as std::move(acc). Length mismatch is not detected: a short second range causes dereference outside its valid range. Operation exceptions propagate.

Examples

#include <array>
#include <iostream>
#include <numeric>

int main() {
    const std::array<int, 3> left{1, 2, 3};
    const std::array<int, 3> right{4, 5, 6};
    const int result = std::inner_product(left.begin(), left.end(), right.begin(), 10);
    std::cout << result << '\n';
}

Result

42

std::inner_product → 42

Sources