我想将以下传统的for循环转换为C++ 11 for-each循环,而无需额外的循环结构:
int a[] = { 5, 6, 7, 8, 9, 10 };
int b[] = { 50, 60, 70, 80, 90, 100 };
// Swap a and b array elements
for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++)
{
a[i] ^= b[i]; b[i] ^= a[i]; a[i] ^= b[i];
}
是否存在任何可能在C++ 11 for-each循环中提供多个变量的方式,例如:
for (int i, int j : ...)
最佳答案
没有内置的方法可以做到这一点。如果可以使用Boost, boost::combine
将同时迭代两个(或多个)范围(Does boost offer make_zip_range?,How can I iterate over two vectors simultaneously using BOOST_FOREACH?):
for (boost::tuple<int&, int&> ij : boost::combine(a, b)) {
int& i = boost::get<0>(ij);
int& j = boost::get<1>(ij);
// ...
}
不幸的是,访问压缩范围的元组元素内的元素非常冗长。 C++ 17将使用结构化绑定(bind)使此内容更具可读性:
for (auto [&i, &j] : boost::combine(a, b)) {
// ...
}
由于不需要中断循环或从封闭函数返回,因此可以将
boost::range::for_each
与循环主体一起使用作为lambda:boost::range::for_each(a, b, [](int& i, int& j)
{
// ...
});