Consider the following code:
vector<int> v;
for(vector<int>::iterator vi = n.begin(), int i = 0;
vi != n.end();
++vi, ++i){}
Is there a reason why this is not allowed? I want to be able to define 2 new counters, both vi and the index i.
This is the explanation from the book C++ Primer:
As in any other declaration, init-statement can define several objects. However, init-statement may be only a single declaration statement. Therefore, all the variables must have the same base type. As one example, we might write a loop to duplicate the elements of a
vector
on the end as follows:// remember the size of v and stop when we get to the original last element for (decltype(v.size()) i = 0, sz = v.size(); i != sz; ++i) v.push_back(v[i]);
In this loop we define both the index,
i
, and the loop control,sz
, in init-statement.
This makes sense, the syntax of for
loop is:
C++11 §6.5.3 The for statement [stmt.for]
The
for
statementfor ( for-init-statement ; condition opt ; expression opt ) statement
for-init-statement
is one statement only. Declaration two different types of variables would make it at least two statements.
Is there a reason why this is not allowed?
Because the arcane declaration syntax of C++ doesn't allow you to declare objects of unrelated types in the same declaration statement; and the initialiser of a for
loop only allows a single declaration statement.
I want to be able to define 2 new counters, both
vi
and the indexi
.
You could declare one or both outside the loop, if you don't mind polluting the surrounding block. Otherwise, you could put them in a stucture:
for (struct {vector<int>::iterator vi; int i;} x = {n.begin(), 0};
x.vi != n.end();
++x.vi, ++x.i) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With