c++ - 改变 boost::combine 的结果

标签 c++ boost compiler-errors c++17

我希望以下代码能够编译并将 v1 的值修改为范围后的 {7, 9, 11, 13, 15}基于for循环。

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

但我收到以下编译错误(使用 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.

我怎样才能实现这个目标?

最佳答案

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

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

Live


关于 boost 元组reference我们可以阅读的网站

Tuples are internally represented as cons lists. For example, the tuple

tuple<A, B, C, D> inherits from the type

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

迭代 boost::combine 返回的所有元素时与 auto& q , qtuple并调用get<N>(q) (其中 N 可以是 0 或 1)我们得到 int& .

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

关于c++ - 改变 boost::combine 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57111203/

相关文章:

c++ - 使用 CRTP 继承

boost 消息队列

c++ - Boost 1_65_1 不使用 OpenSSL 1.1.0g "undefined reference"编译,但使用 "nm"找到

c++ - boost-C++ 库是否与 win98 兼容?

c++ - 删除 vector 中的值时没有匹配的成员函数调用 'erase'

c++ - 读取 .txt 以构建有限数量的项目

c++ - -I 在 g++ 命令中意味着什么?

c++ - 我如何制作指向动态分配对象的指针 vector ?

c++ - 类声明后编译错误,Main 没有 "see"类

java - Java错误: String cannot be resolved into a type(S is uppercase)