algorithm_inner_product

algorithm_inner_product (내적 계산)

std::inner_product는 두 범위의 요소들을 곱해서 합한 내적(inner product)을 계산해요. 커스텀 연산자로 map/reduce 형태의 동작도 가능해요.

출처: cppreference

본문

std::inner_product는 범위 [first1, last1)first2에서 시작하는 std::distance(first1, last1)개 요소의 내적(합의 곱)을 계산하거나, 정렬된 map/reduce 연산을 수행해요. <numeric> 헤더에 정의되어 있어요.

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

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 );
  • 1번 오버로드T 타입의 누적기 accinit으로 초기화하고, 범위의 각 반복자 i1에 대해 acc = acc + (*i1) * (*i2)로 수정해요 (여기서 i2first2의 대응 반복자예요).
  • 2번 오버로드acc = op1(acc, op2(*i1, *i2))로 사용자 정의 연산을 적용해요.

반환값 (Return value)

모든 수정 후의 acc예요.

복잡도 (Complexity)

Nstd::distance(first1, last1)라고 하면 N번의 곱셈(또는 op2 적용)과 N번의 덧셈(또는 op1 적용)이 필요해요.

예제 (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: " << r2 << '\n';
}

출력:

Inner product of a and b: 21
Number of pairwise matches: 2

더 알아보기 (Learn more)

cppreference