Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/inner product"

From cppreference.com
< cpp‎ | algorithm
(Uses {{mark constexpr since c++20}}.)
(Parameters: remove straggling text from pre-P0452 revision)
 
(2 intermediate revisions by 2 users not shown)
Line 3: Line 3:
 
{{dcl begin}}
 
{{dcl begin}}
 
{{dcl header|numeric}}
 
{{dcl header|numeric}}
{{dcla|num=1|notes={{mark constexpr since c++20}}|
+
{{dcla|num=1|constexpr=c++20|
 
template< class InputIt1, class InputIt2, class T >
 
template< class InputIt1, class InputIt2, class T >
 
T inner_product( InputIt1 first1, InputIt1 last1,
 
T inner_product( InputIt1 first1, InputIt1 last1,
 
                 InputIt2 first2, T init );
 
                 InputIt2 first2, T init );
 
}}
 
}}
{{dcla|num=2|notes={{mark constexpr since c++20}}|
+
{{dcla|num=2|constexpr=c++20|
 
template< class InputIt1, class InputIt2, class T,
 
template< class InputIt1, class InputIt2, class T,
 
           class BinaryOp1, class BinaryOp2 >
 
           class BinaryOp1, class BinaryOp2 >
Line 17: Line 17:
 
{{dcl end}}
 
{{dcl end}}
  
Computes inner product (i.e. sum of products) or performs ordered map/reduce operation on the range {{range|first1|last1}} and the range of {{c|std::distance(first1, first2)}} elements beginning at {{c|first2}}.  
+
Computes inner product (i.e. sum of products) or performs ordered map/reduce operation on the range {{range|first1|last1}} and the range of {{c|std::distance(first1, last1)}} elements beginning at {{c|first2}}.  
  
@1@ Initializes the accumulator {{c|acc}} (of type {{tt|T}}) with the initial value {{c|init}} and then  modifies it with the expression {{rev inl|until=c++11|{{c|1=acc = acc + (*i1) * (*i2)}}}}{{rev inl|since=c++11|{{c|1=acc = std::move(acc) + (*i1) * (*i2)}}}} for every iterator {{c|i1}} in the range {{range|first1|last1}} in order and its corresponding iterator {{c|i2}} in the range beginning at {{c|first2}}. For built-in meaning of + and *, this computes inner product of the two ranges.
+
@1@ Initializes the accumulator {{c|acc}} (of type {{tt|T}}) with the initial value {{c|init}} and then  modifies it with the expression {{rev inl|until=c++20|{{c|1=acc = acc + (*i1) * (*i2)}}}}{{rev inl|since=c++20|{{c|1=acc = std::move(acc) + (*i1) * (*i2)}}}} for every iterator {{c|i1}} in the range {{range|first1|last1}} in order and its corresponding iterator {{c|i2}} in the range beginning at {{c|first2}}. For built-in meaning of + and *, this computes inner product of the two ranges.
  
@2@ Initializes the accumulator {{c|acc}} (of type {{tt|T}}) with the initial value {{c|init}} and then  modifies it with the expression {{rev inl|until=c++11|{{c|1=acc = op1(acc, op2(*i1, *i2))}}}}{{rev inl|since=c++11|{{c|1=acc = op1(std::move(acc), op2(*i1, *i2))}}}} for every iterator {{c|i1}} in the range {{range|first1|last1}} in order and its corresponding iterator {{c|i2}} in the range beginning at {{c|first2}}.
+
@2@ Initializes the accumulator {{c|acc}} (of type {{tt|T}}) with the initial value {{c|init}} and then  modifies it with the expression {{rev inl|until=c++20|{{c|1=acc = op1(acc, op2(*i1, *i2))}}}}{{rev inl|since=c++20|{{c|1=acc = op1(std::move(acc), op2(*i1, *i2))}}}} for every iterator {{c|i1}} in the range {{range|first1|last1}} in order and its corresponding iterator {{c|i2}} in the range beginning at {{c|first2}}.
  
 
Given {{c|last2}} as the {{c|std::distance(first1, last1)}}{{su|b=th}} next iterator of {{c|first2}}, if any of the following conditions is satisfied, the behavior is undefined:
 
Given {{c|last2}} as the {{c|std::distance(first1, last1)}}{{su|b=th}} next iterator of {{c|first2}}, if any of the following conditions is satisfied, the behavior is undefined:
Line 38: Line 38:
 
{{par hreq}}
 
{{par hreq}}
 
{{par req named|InputIt1, InputIt2|InputIterator}}
 
{{par req named|InputIt1, InputIt2|InputIterator}}
{{par req named|ForwardIt1, ForwardIt2|ForwardIterator}}
 
 
{{par end}}
 
{{par end}}
  
Line 53: Line 52:
 
     while (first1 != last1)
 
     while (first1 != last1)
 
     {
 
     {
         init = std::move(init) + (*first1) * (*first2); // std::move since C++11
+
         init = std::move(init) + (*first1) * (*first2); // std::move since C++20
 
         ++first1;
 
         ++first1;
 
         ++first2;
 
         ++first2;
Line 69: Line 68:
 
     while (first1 != last1)
 
     while (first1 != last1)
 
     {
 
     {
         init = op1(std::move(init), op2(*first1, *first2)); // std::move since C++11
+
         init = op1(std::move(init), op2(*first1, *first2)); // std::move since C++20
 
         ++first1;
 
         ++first1;
 
         ++first2;
 
         ++first2;
Line 110: Line 109:
 
{{dr list begin}}
 
{{dr list begin}}
 
{{dr list item|wg=lwg|dr=242|std=C++98|before={{c|op1}} and {{c|op2}} could not have side effects|after=they cannot modify the ranges involved}}
 
{{dr list item|wg=lwg|dr=242|std=C++98|before={{c|op1}} and {{c|op2}} could not have side effects|after=they cannot modify the ranges involved}}
{{dr list item|wg=lwg|dr=2055|paper=P0616R0|std=C++11|before={{c|acc}} was not moved while being accumulated|after=it is moved}}
 
 
{{dr list end}}
 
{{dr list end}}
  

Latest revision as of 14:31, 26 October 2024

 
 
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
(C++11)                (C++11)(C++11)

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
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
(C++11)
inner_product
Operations on uninitialized memory
 
 
Defined in header <numeric>
template< class InputIt1, class InputIt2, class T >

T inner_product( InputIt1 first1, InputIt1 last1,

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

Computes inner product (i.e. sum of products) or performs ordered map/reduce operation on the range [first1last1) and the range of std::distance(first1, last1) elements beginning at first2.

1) Initializes the accumulator acc (of type T) with the initial value init and then modifies it with the expression acc = acc + (*i1) * (*i2)(until C++20)acc = std::move(acc) + (*i1) * (*i2)(since C++20) for every iterator i1 in the range [first1last1) in order and its corresponding iterator i2 in the range beginning at first2. For built-in meaning of + and *, this computes inner product of the two ranges.
2) Initializes the accumulator acc (of type T) with the initial value init and then modifies it with the expression acc = op1(acc, op2(*i1, *i2))(until C++20)acc = op1(std::move(acc), op2(*i1, *i2))(since C++20) for every iterator i1 in the range [first1last1) in order and its corresponding iterator i2 in the range beginning at first2.

Given last2 as the std::distance(first1, last1)th next iterator of first2, if any of the following conditions is satisfied, the behavior is undefined:

  • T is not CopyConstructible.
  • T is not CopyAssignable.
  • op1 or op2 modifies any element of [first1last1) or [first2last2).
  • op1 or op2 invalidates any iterator or subrange in [first1last1] or [first2last2].

Contents

[edit] Parameters

first1, last1 - the first range of elements
first2 - the beginning of the second range of elements
init - initial value of the sum of the products
op1 - binary operation function object that will be applied. This "sum" function takes a value returned by op2 and the current value of the accumulator and produces a new value to be stored in the accumulator.

The signature of the function should be equivalent to the following:

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

The signature does not need to have const &.
The types  Type1 and  Type2 must be such that objects of types T and Type3 can be implicitly converted to  Type1 and  Type2 respectively. The type Ret must be such that an object of type T can be assigned a value of type Ret. ​

op2 - binary operation function object that will be applied. This "product" function takes one value from each range and produces a new value.

The signature of the function should be equivalent to the following:

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

The signature does not need to have const &.
The types  Type1 and  Type2 must be such that objects of types InputIt1 and InputIt2 can be dereferenced and then implicitly converted to  Type1 and  Type2 respectively. The type Ret must be such that an object of type Type3 can be assigned a value of type Ret. ​

Type requirements
-
InputIt1, InputIt2 must meet the requirements of LegacyInputIterator.

[edit] Return value

acc after all modifications.

[edit] Possible implementation

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;
}

[edit] Notes

The parallelizable version of this algorithm, std::transform_reduce, requires op1 and op2 to be commutative and associative, but std::inner_product makes no such requirement, and always performs the operations in the order given.

[edit] 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 between a and b: " <<  r2 << '\n';
}

Output:

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

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 242 C++98 op1 and op2 could not have side effects they cannot modify the ranges involved

[edit] See also

applies an invocable, then reduces out of order
(function template) [edit]
sums up or folds a range of elements
(function template) [edit]
computes the partial sum of a range of elements
(function template) [edit]