Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 for each loop with more than one variable

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 : ...)
like image 924
Seshadri R Avatar asked May 26 '26 09:05

Seshadri R


1 Answers

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)
{
    // ...
});
like image 107
ecatmur Avatar answered May 27 '26 23:05

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!