问题描述
我需要总结一些向量;也就是说,我想对每个向量的 nth
个元素求和,并用结果创建一个新向量。 (我已经确保输入向量的大小都相同。)我想使用出色的库。我已经尝试过:
I need to sum up some vectors; that is, I want to sum the nth
elements of every vector and make a new vector with the result. (I've already ensured that the input vectors are all the same size.) I'd like to do this with the excellent range-v3 library. I've tried this:
// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <map>
#include <range/v3/all.hpp>
int main()
{
std::cout << "Hello, Wandbox!" << std::endl;
std::vector< int > v1{ 1,1,1};
std::vector< int> v2{1,1,1};
auto va = ranges::view::zip( v1, v2 )
| ranges::view::transform(
[](auto&& tuple){ return ranges::accumulate( tuple, 0.0 ); }
);
}
我收到了我无法致电 ranges :: accumulate
像这样。我觉得这是一件很简单的事情,我只是不太了解。
I get the error that I can't call to ranges::accumulate
like this. I feel like this is a simple thing that I'm just not quite seeing.
请告知
编辑:
我在这里问一个后续问题:
推荐答案
您可以使用对一个元组的值求和,而不是累加
:
auto sum_tuple = [](auto&& tuple) {
return std::apply([](auto... v) {
return (v + ...);
}, tuple );
};
auto va = ranges::views::zip( v1, v2 )
| ranges::views::transform(sum_tuple);
这里是。显示的示例也包含两个以上的向量。
Here's a demo. Show's an example with more than 2 vectors as well.
此外,请注意, ranges :: view
已过时赞成 ranges :: views
。
Also, note that ranges::view
has been deprecated in favor of ranges::views
.
这篇关于范围v3的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!