Sum vector with range-v3

喜欢而已 提交于 2020-07-22 04:16:45

问题


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 ); }
    );

}

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.

Please advise

EDIT: I ask a follow-on question here: How to zip vector of vector with range-v3


回答1:


You can use std::apply to sum over values of a tuple, instead of 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.

Also, note that ranges::view has been deprecated in favor of ranges::views.



来源:https://stackoverflow.com/questions/61785434/sum-vector-with-range-v3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!