Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring several new counters in a for loop

Tags:

c++

c

stl

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.

like image 259
Henry Henrinson Avatar asked Dec 20 '22 22:12

Henry Henrinson


2 Answers

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 statement

for ( 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.

like image 86
Yu Hao Avatar answered Dec 22 '22 11:12

Yu Hao


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 index i.

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) {}
like image 30
Mike Seymour Avatar answered Dec 22 '22 11:12

Mike Seymour