11为每个循环与多个变量

11为每个循环与多个变量

本文介绍了C ++ 11为每个循环与多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 <$ 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,那么可以同时迭代两个(或多个)范围(作为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为每个循环与多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:33