Search code examples
c++accumulaterange-v3

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. (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


Solution

  • 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. Shows an example with more than 2 vectors as well.

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