std::inner_product

Header: <numeric>

Computes inner product (i.e. sum of products) or performs ordered map/reduce operation on the range [first1,last1) and the range of std::distance(first1, last1) elements beginning at first2.

# Declarations

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

(constexpr since C++20)

template< class InputIt1, class InputIt2, class T,
class BinaryOp1, class BinaryOp2 >
T inner_product( InputIt1 first1, InputIt1 last1,
InputIt2 first2, T init,
BinaryOp1 op1, BinaryOp2 op2 );

(constexpr since C++20)

# Parameters

# Return value

acc after all modifications.

# Notes

The parallelizable version of this algorithm, std::transform_reduce, requires op1 and op2 to be commutative and associative, but std::inner_product makes no such requirement, and always performs the operations in the order given.

# Example

#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
 
int main()
{
    std::vector<int> a{0, 1, 2, 3, 4};
    std::vector<int> b{5, 4, 2, 3, 1};
 
    int r1 = std::inner_product(a.begin(), a.end(), b.begin(), 0);
    std::cout << "Inner product of a and b: " << r1 << '\n';
 
    int r2 = std::inner_product(a.begin(), a.end(), b.begin(), 0,
                                std::plus<>(), std::equal_to<>());
    std::cout << "Number of pairwise matches between a and b: " <<  r2 << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 242C++98op1 and op2 could not have side effectsthey cannot modify the ranges involved

# See also