std::inner_product()는 두 개의 범위를 이용해 내적(inner product)을 계산한다.
<numeric> 헤더에 포함되어 있으며, 이 함수는 두 범위의 각 원소를 곱한 뒤 그 합을 계산하는 데 유용하며, 벡터 내적을 구할 때 자주 사용된다.
template<class InputIterator1, class InputIterator2, class T>
T inner_product(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, T init);
first1, last1: 첫 번째 범위의 시작과 끝 반복자first2: 두 번째 범위의 시작 반복자init: 합산을 시작할 초기값std::inner_product()는 다음과 같은 연산을 수행한다.
init을 더한 결과를 반환한다.#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;
}
vec1과 vec2의 원소를 각각 곱하여 합산합니다.#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이 더해진 결과가 반환된다.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()와 동일하게 작동한다.first1, last1의 범위는 반닫힌 범위 [first1, last1)를 따른다.