我希望以下代码能够编译并将 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.
我怎样才能实现这个目标?
最佳答案
因为b
是 tuple
(在 boost 中,它是内部 cons
辅助模板,采用 2 个参数作为 head 和 tail),其 head 引用 int
(作为原始元组的第二个字段 - 由 combine
返回),您可以使用 boost::get
阅读此内容:
for(auto&& [a, b] : boost::combine(v1, v2)) {
a += boost::get<0>(b);
}
关于 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
, q
是 tuple
并调用get<N>(q)
(其中 N
可以是 0 或 1)我们得到 int&
.
但在结构化绑定(bind)版本中 - auto&& [a,b]
, a
指int&
和b
指 boost 内部cons
struct,这就是为什么我们需要使用 get<0>
访问输入序列中的第二个整数值。
关于c++ - 改变 boost::combine 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57111203/