[英]Sum vector with range-v3
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.也就是说,我想对每个向量的
nth
元素求和,并用结果创建一个新向量。 (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. (我已经确保输入向量的大小都相同。)我想使用出色的range-v3库来做到这一点。 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 ); }
);
}
I get the error that I can't call to ranges::accumulate
like this.我收到无法像这样调用
ranges::accumulate
的错误。 I feel like this is a simple thing that I'm just not quite seeing.我觉得这是一件简单的事情,我只是不太了解。
Please advise请指教
EDIT: I ask a follow-on question here: How to zip vector of vector with range-v3编辑:我在这里问一个后续问题: How to zip vector of vector with range-v3
You can use std::apply
to sum over values of a tuple, instead of accumulate
:您可以使用
std::apply
来对元组的值求和,而不是accumulate
:
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.
Show 也是一个包含 2 个以上向量的示例。
Also, note that ranges::view
has been deprecated in favor of ranges::views
.另外,请注意
ranges::view
已被弃用,取而代之的是ranges::views
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.