【问题标题】:Sum vector with range-v3使用 range-v3 求和向量
【发布时间】:2020-05-13 21:46:13
【问题描述】:

我需要总结一些向量;也就是说,我想对每个向量的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

【问题讨论】:

    标签: c++ accumulate range-v3


    【解决方案1】:

    您可以使用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。 Show 也是一个包含 2 个以上向量的示例。

    另外,请注意 ranges::view 已被弃用,取而代之的是 ranges::views

    【讨论】:

    • 使用std::apply 效果很好。为什么不ranges::accumulate? (感谢您的弃用提示。)
    • accumulate 需要具有beginend 的范围,即输入必须满足range 概念。 tuple 没有那个接口,所以不满足这个概念。
    • 在我的示例中,tuple 不只是另一个range,因为它是ranges::view::zip 的结果吗?
    • 否,请参见例如 thiszip 返回 tuple
    • 啊,我不知道它返回了std::tuple。我只是在示例中使用了tuple 作为任意名称。
    猜你喜欢
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2019-12-16
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多