std::inner_product
: cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| (1) | ||
template< class InputIt1, class InputIt2, class T > T inner_product( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init ); |
(C++20) | |
template< class InputIt1, class InputIt2, class T > constexpr T inner_product( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init ); |
(C++20) | |
| (2) | ||
template<class InputIt1, class InputIt2, class T, class BinaryOperation1, class BinaryOperation2> T inner_product( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryOperation1 op1, BinaryOperation2 op2 ); |
(C++20) | |
template<class InputIt1, class InputIt2, class T, class BinaryOperation1, class BinaryOperation2> constexpr T inner_product( InputIt1 first1, InputIt1 last1, InputIt2 first2, T init, BinaryOperation1 op1, BinaryOperation2 op2 ); |
(C++20) | |
[first1, last1) first2 () map/reduce
1)
+ * 2
acc init last1
|
|
(C++20) |
|
|
(C++20) |
2)
acc init last1
|
|
(C++20) |
|
|
(C++20) |
|
|
(C++11) |
|
|
(C++11) |
| first1, last1 | - | 1 |
| first2 | - | 2 |
| init | - | |
| op1 | - | op2
|
| op2 | - | 1
|
-InputIt1, InputIt2 LegacyInputIterator
| ||
-ForwardIt1, ForwardIt2 LegacyForwardIterator
| ||
-T CopyAssignable CopyConstructible
| ||
acc
| 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;
}
|
| 2 |
template<class InputIt1, class InputIt2,
class T,
class BinaryOperation1, class BinaryOperation2>
constexpr // since C++20
T inner_product(InputIt1 first1, InputIt1 last1,
InputIt2 first2, T init,
BinaryOperation1 op1
BinaryOperation2 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
Run this code
#include <numeric>
#include <iostream>
#include <vector>
#include <functional>
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';
}
:
Inner product of a and b: 21
Number of pairwise matches between a and b: 2
(C++17) |
reduce () |
| () | |
| () |