C ++ 11为每个循环与多个变量 [英] C++11 for each loop with more than one variable
问题描述
<$ c $ c> int a [] = {5,6,7,8,9,10};
int b [] = {50,60,70,80,90,100};
//交换a和b数组元素
(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循环中:
$ $ $ $ $ $ $ $ $ $ $ $ $ b
没有内置的方法来执行此操作。如果您可以使用Boost,那么 boost :: combine
可以同时迭代两个(或多个)范围(,
for(boost :: tuple< int&; int&> ij:boost :: combine(a,b)){
int& i = boost :: get(0)(i,j);
int& j = boost :: get(i,j);
// ...
}
不幸地访问元组中的元素压缩范围的元素非常冗长。 (auto [& i,& j])使用结构化绑定,C ++ 17将使这个更加可读:
:boost :: combine(a,b)){
// ...
}
因为你不需要跳出循环或从封闭函数返回,所以你可以使用 boost :: range :: for_each
作为lambda的循环体:
boost :: range :: for_each(a,b,[](int& i,int& j)
{
// ...
});
I would like to translate the following traditional for loop into a C++11 for-each loop without extra looping constructs:
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];
}
Does there exist any way by which it is possible to provide more than one variable in the C++11 for-each loop like:
for (int i, int j : ...)
There is no built-in way to do this. If you can use Boost, boost::combine
will work for iterating two (or more) ranges simultaneously (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);
// ...
}
Unfortunately accessing the elements within the tuple elements of the zipped range is highly verbose. C++17 will make this much more readable using structured binding:
for (auto [&i, &j] : boost::combine(a, b)) {
// ...
}
Since you don't need to break out of the loop or return from the enclosing function, you could use boost::range::for_each
with the body of your loop as a lambda:
boost::range::for_each(a, b, [](int& i, int& j)
{
// ...
});
这篇关于C ++ 11为每个循环与多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!