std::inner_product
来自cppreference.com
| 在标头 <numeric> 定义
|
||
| (1) | (C++20 起为 constexpr) |
|
| (2) | (C++20 起为 constexpr) |
|
在范围 [first1, last1) 和从 first2 开始的包含 std::distance(first1, last1) 个元素的范围上计算内积(即积之和)或进行有序映射/规约操作。
1) 以初值
init 初始化(具有 T 类型的)累加器 acc,然后按顺序对范围 [first1, last1) 的每个迭代器 i1 和它在从 first2 开始的范围中对应的迭代器 i2 通过 表达式 acc = acc + (*i1) * (*i2)(C++20 前)acc = std::move(acc) + (*i1) * (*i2)(C++20 起) 予以修改(进行累加)。对于 + 与 * 的内建含义,此算法计算两个范围的内积。2) 以初值
init 初始化(具有 T 类型的)累加器 acc,然后按顺序对范围 [first1, last1) 的每个迭代器 i1 和它在从 first2 开始的范围中对应的迭代器 i2 通过 表达式 acc = op1(acc, op2(*i1, *i2))(C++20 前)acc = op1(std::move(acc), op2(*i1, *i2))(C++20 起) 予以修改(进行累加)。给定 last2 为 first2 的下 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 所返回的值和当前累加器的值,并产生向累加器存储的新值。该函数的签名应当等价于:
签名中并不需要有 |
| op2 | - | 被使用的二元函数对象。此“求积”函数从每个范围接收一个值并产生新值。 该函数的签名应当等价于:
签名中并不需要有 |
| 类型要求 | ||
-InputIt1, InputIt2 必须满足老式输入迭代器 (LegacyInputIterator) 。
| ||
返回值
完成所有修改后的 acc。
可能的实现
| inner_product (1) |
|---|
template<class InputIt1, class InputIt2, class T>
constexpr // C++20 起
T inner_product(InputIt1 first1, InputIt1 last1, InputIt2 first2, T init)
{
while (first1 != last1)
{
init = std::move(init) + (*first1) * (*first2); // C++20 起有 std::move
++first1;
++first2;
}
return init;
}
|
| inner_product (2) |
template<class InputIt1, class InputIt2, class T,
class BinaryOp1, class BinaryOp2>
constexpr // 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)); // C++20 起有 std::move
++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';
}
输出:
a 和 b 的内积:21
a 和 b 中匹配的对数:2
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 242 | C++98 | op1 和 op2 不能有任何副作用
|
它们不能修改涉及到的范围 |
