Namespaces
Variants

std:: inner_product

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
헤더 파일에 정의됨 <numeric>
template < class InputIt1, class InputIt2, class T >

T inner_product ( InputIt1 first1, InputIt1 last1,

InputIt2 first2, T init ) ;
(1) (C++20부터 constexpr)
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) (C++20부터 constexpr)

내적(즉, 곱의 합)을 계산하거나 범위 [ first1 , last1 ) std:: distance ( first1, last1 ) 개의 원소로 이루어진 first2 부터 시작하는 범위에 대해 정렬된 map/reduce 연산을 수행합니다.

1) 누산기 acc (타입 T )를 초기값 init 로 초기화한 후, 범위 [ first1 , last1 ) 내의 모든 반복자 i1 first2 에서 시작하는 범위의 대응하는 반복자 i2 에 대해 다음 표현식으로 수정합니다: acc = acc + ( * i1 ) * ( * i2 ) (C++20 이전) acc = std :: move ( acc ) + ( * i1 ) * ( * i2 ) (C++20 이후) . +와 *의 내장 의미에 대해서는, 이는 두 범위의 내적을 계산합니다.
2) 누산기 acc (타입 T )를 초기값 init 로 초기화한 후, 범위 [ first1 , last1 ) 내의 모든 반복자 i1 first2 에서 시작하는 범위의 해당 반복자 i2 에 대해 순서대로 다음 표현식으로 수정합니다: acc = op1 ( acc, op2 ( * i1, * i2 ) ) (C++20 이전) acc = op1 ( std :: move ( acc ) , op2 ( * i1, * i2 ) ) (C++20 이후)

last2 std:: distance ( first1, last1 ) 번째 다음 반복자로 지정할 때, 다음 조건 중 하나라도 만족되면 동작은 정의되지 않습니다:

  • T CopyConstructible 이 아닙니다.
  • T CopyAssignable 이 아닙니다.
  • op1 또는 op2 [ first1 , last1 ) 또는 [ first2 , last2 ) 의 어떤 요소도 수정하는 경우.
  • op1 또는 op2 [ first1 , last1 ] 또는 [ first2 , last2 ] 의 어떤 반복자나 부분 범위를 무효화하는 경우.

목차

매개변수

first1, last1 - 요소들의 범위 를 정의하는 반복자 쌍
first2 - 두 번째 요소 범위의 시작점
init - 곱들의 합에 대한 초기값
op1 - 적용될 이항 연산 함수 객체. 이 "합" 함수는 op2 가 반환한 값과 누산기의 현재 값을 취해 누산기에 저장될 새 값을 생성합니다.

함수의 시그니처는 다음에 해당해야 합니다:

Ret fun ( const Type1 & a, const Type2 & b ) ;

시그니처에 const & 이 있을 필요는 없습니다.
Type1 Type2 타입은 T Type3 타입의 객체가 각각 Type1 Type2 로 암시적으로 변환될 수 있어야 합니다. Ret 타입은 T 타입의 객체에 Ret 타입의 값을 할당할 수 있어야 합니다. ​

op2 - 적용될 이항 연산 함수 객체. 이 "곱" 함수는 각 범위에서 하나의 값을 취해 새 값을 생성합니다.

함수의 시그니처는 다음에 해당해야 합니다:

Ret fun ( const Type1 & a, const Type2 & b ) ;

시그니처에 const & 이 있을 필요는 없습니다.
Type1 Type2 타입은 InputIt1 InputIt2 타입의 객체가 역참조된 후 각각 Type1 Type2 로 암시적으로 변환될 수 있어야 합니다. Ret 타입은 Type3 타입의 객체에 Ret 타입의 값을 할당할 수 있어야 합니다. ​

타입 요구사항
-
InputIt1, InputIt2 LegacyInputIterator 요구사항을 충족해야 합니다.

반환값

acc 모든 수정 후.

가능한 구현

inner_product (1)
template<class InputIt1, class InputIt2, class T>
constexpr // since C++20
T inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init)
{
    while (first1 != last1)
    {
        init = std::move(init) + (*first1) * (*first2); // std::move since C++20
        ++first1;
        ++first2;
    }
    return init;
}
inner_product (2)
template<class InputIt1, class InputIt2, class T,
         class BinaryOp1, class BinaryOp2>
constexpr // since C++20
T inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init,
                BinaryOp1 op1, BinaryOp2 op2)
{
    while (first1 != last1)
    {
        init = op1(std::move(init), op2(*first1, *first2)); // std::move since C++20
        ++first1;
        ++first2;
    }
    return init;
}

참고 사항

이 알고리즘의 병렬화 가능 버전인 std::transform_reduce op1 op2 가 교환 법칙과 결합 법칙을 만족해야 하지만, std::inner_product 는 이러한 요구 사항이 없으며 항상 주어진 순서대로 연산을 수행합니다.

예제

#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 << "a와 b의 내적: " << r1 << '\n';
    int r2 = std::inner_product(a.begin(), a.end(), b.begin(), 0,
                                std::plus<>(), std::equal_to<>());
    std::cout << "a와 b 간의 쌍별 일치 개수: " <<  r2 << '\n';
}

출력:

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

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 242 C++98 op1 op2 가 부작용을 가질 수 없었음 관련 범위를 수정할 수 없음

참고 항목

호출 가능 객체를 적용한 후 비순차적으로 reduce 수행
(함수 템플릿)
요소 범위의 합계 계산 또는 폴드
(함수 템플릿)
요소 범위의 부분 합계 계산
(함수 템플릿)