如何通过stl容器和算法库计算两个向量的内积?

How to calc inner product of two vectors by stl container and algorithm libraries?

确实有很多方法:

assert(v1.size() == v2.size());
for (auto&& i = 0; i < v1.size(); ++i) {
    acc += v1[i]*v2[i];
}

但是python中有一个zip运算符,所以python代码会很简单,如下代码:

acc = accumulate([ele1 * ele2 for ele1, ele2 in zip(v1, v2)])

我的问题是:是否有任何类似的方法来编写一些样式与 python 代码相同的代码?特别是 std::algorithm 图书馆。

扩展@G.M. 的评论

给出

std::vector<int> v1, v2;
assert(v1.size() == v2.size());

可以获得内积

auto acc = std::inner_product(v1.begin(), v1.end(), v2.begin(), 0);

请注意,第二个范围仅作为开始传递。 std::inner_product的前置条件相当于v1.size() <= v2.size(),比你指定的要弱。