突变boost :: combine的结果

Mat*_*sen 2 c++ boost compiler-errors c++17

我会希望下面的代码进行编译和修改的值v1{7, 9, 11, 13, 15}在基于范围循环后。

#include <boost/range/combine.hpp>
#include <vector>

int main()
{
  std::vector<int> v1{1, 2, 3, 4, 5};
  std::vector<int> v2{6, 7, 8, 9, 10};
  for(auto&& [a, b] : boost::combine(v1, v2)) {
    a += b;
  }


  return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是出现以下编译错误(带有g++ -std=c++17):

error: invalid operands to binary expression ('int' and 'boost::tuples::cons<int &, boost::tuples::cons<int &, boost::tuples::null_type> >::tail_type' (aka
      'boost::tuples::cons<int &, boost::tuples::null_type>'))
    a += b;
    ~ ^  ~
1 error generated.
Run Code Online (Sandbox Code Playgroud)

我该如何实现?

raf*_*x07 5

因为btuple(在boost中,它是内部cons帮助器模板,使用2个参数分别作为headtail),其head引用了int(作为原始元组的第二个字段-由返回combine),因此您可以boost::get阅读以下内容:

  for(auto&& [a, b] : boost::combine(v1, v2)) {
    a += boost::get<0>(b);
  }
Run Code Online (Sandbox Code Playgroud)

生活


在boost元组参考站点上,我们可以阅读

元组在内部表示为缺点列表。例如,元组

tuple<A, B, C, D> 从类型继承

cons<A, cons<B, cons<C, cons<D, null_type> > > >

当迭代boost::combinewith auto& qqis tuple和通过调用get<N>(q)N可以为0或1)返回的所有元素时,我们得到int&

但在结构绑定版本- auto&& [a,b]a指的是int&b是指提高内部cons结构,这就是为什么我们需要使用get<0>访问从输入序列中的第二个整数值。