Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ 11 for container loop for multiple items

I was wondering either it is possible in the c++11 syntax to use the new container based for loop for multiple items, for example:

std::vector<double> x;
std::vector<double> y;

for (double& xp, yp : x, y)
{
     std::cout << xp << yp << std::endl;
}

I was not able to find any information about using this loop for more than one container. I would appreciate all help.

Example effect in the classic for loop:

std::vector<double>::iterator itX = m_x.begin();
std::vector<double>::iterator itY = m_y.begin();

for (uint32_t i = 0; i < m_x.size(); i++, itX++, itY++)
{
    // operations on the m_x and m_y vectors
}
like image 243
Łukasz Przeniosło Avatar asked Nov 28 '25 01:11

Łukasz Przeniosło


1 Answers

There is a request in the language working group to support a very similar syntax to iterate simultaneously on many containers:

Section: 6.5.4 [stmt.ranged] Status: Open Submitter: Gabriel Dos Reis

Opened: 2013-01-12 Last modified: 2015-05-22

Discussion:

The new-style 'for' syntax allows us to dispense with administrative iterator declarations when iterating over a single sequence. The burden and noise remain, however, when iterating over two or more sequences simultaneously. We should extend the syntax to allow that. E.g. one should be able to write:

for (auto& x : v; auto& y : w)
  a = combine(v, w, a);

instead of the noisier

auto p1 = v.begin();
auto q1 = v.end();
auto p2 = w.begin();
auto q2 = w.end();
while (p1 < q1 and p2 < q2) {
   a = combine(*p1, *p2, a);
   ++p1;
   ++p2;
}

See http://cplusplus.github.io/EWG/ewg-active.html#43

So it could happen but not in the near future.

Meanwhile the best choice is probably the classical for loop.

like image 81
manlio Avatar answered Nov 29 '25 14:11

manlio