std::inner_product()

김민수·2025년 1월 9일

C++

목록 보기
48/68

std::inner_product()는 두 개의 범위를 이용해 내적(inner product)을 계산한다.
<numeric> 헤더에 포함되어 있으며, 이 함수는 두 범위의 각 원소를 곱한 뒤 그 합을 계산하는 데 유용하며, 벡터 내적을 구할 때 자주 사용된다.


1. 정의

template<class InputIterator1, class InputIterator2, class T>
T inner_product(InputIterator1 first1, InputIterator1 last1,
                InputIterator2 first2, T init);
  • first1, last1: 첫 번째 범위의 시작과 끝 반복자
  • first2: 두 번째 범위의 시작 반복자
  • init: 합산을 시작할 초기값


2. 동작 방식

std::inner_product()는 다음과 같은 연산을 수행한다.

result=init+(range1[0]×range2[0])+(range1[1]×range2[1])+result = init + (range1[0] \times range2[0]) + (range1[1] \times range2[1]) + \ldots

  • 각 범위의 원소들을 순차적으로 곱한 후 합산한다.
  • 두 벡터(혹은 배열)의 크기가 동일해야 정상적으로 작동한다.
  • 초기값 init을 더한 결과를 반환한다.


3. 코드 예시

두 벡터의 내적 계산

#include <iostream>
#include <vector>
#include <numeric>  // std::inner_product

int main() {
    std::vector<int> vec1 = {1, 2, 3, 4};
    std::vector<int> vec2 = {5, 6, 7, 8};
    
    int result = std::inner_product(vec1.begin(), vec1.end(), vec2.begin(), 0);

    std::cout << "Inner product: " << result << std::endl;  // 출력: 70
    return 0;
}
  • vec1vec2의 원소를 각각 곱하여 합산합니다.
  • result=0+(1×5)+(2×6)+(3×7)+(4×8)=70result = 0 + (1 \times 5) + (2 \times 6) + (3 \times 7) + (4 \times 8) = 70

초기값을 설정한 내적 계산

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> vec1 = {1, 2, 3};
    std::vector<int> vec2 = {4, 5, 6};
    
    int result = std::inner_product(vec1.begin(), vec1.end(), vec2.begin(), 10);

    std::cout << "Inner product with initial value 10: " << result << std::endl;  // 출력: 52
    return 0;
}
  • 초기값 10이 더해진 결과가 반환된다.
  • result=10+(1×4)+(2×5)+(3×6)=52result = 10 + (1 \times 4) + (2 \times 5) + (3 \times 6) = 52


4. 사용자 정의 연산을 이용한 std::inner_product()

std::inner_product()는 기본적으로 곱셈덧셈 연산을 사용하지만, 필요에 따라 사용자 정의 연산을 지정할 수 있다.

template<class InputIterator1, class InputIterator2, class T,
         class BinaryOperation1, class BinaryOperation2>
T inner_product(InputIterator1 first1, InputIterator1 last1,
                InputIterator2 first2, T init,
                BinaryOperation1 binary_op1, BinaryOperation2 binary_op2);
  • binary_op1: 누적 합산 연산을 정의
  • binary_op2: 두 원소의 연산을 정의

사용자 정의 연산 사용

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> vec1 = {1, 2, 3};
    std::vector<int> vec2 = {4, 5, 6};
    
    int result = std::inner_product(vec1.begin(), vec1.end(), vec2.begin(), 0,
                                    std::plus<int>(), std::multiplies<int>());

    std::cout << "Inner product with custom operations: " << result << std::endl;  // 출력: 32
    return 0;
}
  • std::plus<int>(): 누적 합산 연산을 덧셈으로 정의
  • std::multiplies<int>(): 두 원소의 연산을 곱셈으로 정의
  • 결과는 기본 std::inner_product()와 동일하게 작동한다.

5. 주의사항

  1. 두 범위의 크기가 같아야 함
    두 범위의 크기가 다를 경우, 정의되지 않은 동작이 발생할 수 있다.
  2. 반복자 범위 주의
    반복자 first1, last1의 범위는 반닫힌 범위 [first1, last1)를 따른다.
profile
안녕하세요

0개의 댓글