inner_product

inner_product (내적/일반화 내적)

두 범위의 원소를 짝지어 곱하고(기본) 그 결과를 누적해 합계(내적)를 구하는 알고리즘이에요. 사용자 정의 연산으로 일반화할 수 있어요. <numeric> 헤더에 있어요.

출처: cppreference

본문

inner_product는 두 범위의 대응 원소 쌍의 곱의 합(내적)을 계산해요.

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

사용자 정의 이진 연산으로 일반화한 버전도 있어요.

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 );   // (2)
    1. init에 시작해 각 쌍 (a, b)에 대해 acc = acc + (a * b)를 계산해요.
    1. op1(누적)과 op2(요소 쌍 결합)로 계산해요.
std::vector<double> a{1.0, 2.0, 3.0};
std::vector<double> b{4.0, 5.0, 6.0};
double dot = std::inner_product(a.begin(), a.end(), b.begin(), 0.0);
// 1*4 + 2*5 + 3*6 = 32

벡터 내적(dot product)이 대표적인 용도예요. op2를 곱셈 대신 다른 연산으로 바꾸면 다양한 "쌍 결합 후 누적" 패턴을 만들 수 있어요. (표준 병렬/요소 쌍 방식을 일반화한 최신 대안으로 std::transform_reduce가 있어요.)

더 알아보기 (Learn more)

cppreference