c++ 范围为v3的和向量

vd8tlhqk  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(90)

我需要对一些向量求和;也就是说,我想对每个向量的nth元素求和,并使用结果生成一个新的向量。(我已经确保输入向量的大小都相同。)我想使用出色的range-v3库来完成此操作。我已经尝试过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。我觉得这是一个简单的事情,我只是不太明白。
请告知
编辑:我在这里问一个后续问题:How to zip vector of vector with range-v3

a9wyjsp7

a9wyjsp71#

您可以使用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);

字符串
这里有一个demo。显示了一个包含两个以上向量的例子。
另外,请注意,ranges::view已被弃用,而支持ranges::views

esyap4oy

esyap4oy2#

您可以将zip_withstd::plus<int>一起使用。Demo(https://godbolt.org/z/ac3czj741)

auto va = ranges::view::zip_with(std::plus<int>{}, v1, v2));

字符串

相关问题