How to write a for loop that uses both an iterator and an index counter?

The issue is with this part of the for loop:

std::vector<Foo>::iterator it = var.begin(), i = 0

C++ is interpreting this not as two comma-separated statements, but as a variable declaration for a variable named it that's an iterator, and as a new declaration of a variable i that's an iterator and initialized to 0. The error is because you can't initialize a vector iterator to 0.

To fix this, you'll need to hoist the definition outside of the loop:

int i = 0;
std::vector<Foo>::iterator it = var.begin();
for(; it < var.end(); it++, i++ )
{
     // ...
}

Or move the initialization of i outside the loop:

int i = 0;
for( std::vector<Foo>::iterator it = var.begin(); it < var.end(); it++, i++ )
{
    // ...
}

Here's another option. If you need to keep track of the index into the vector you're currently looking at, you could consider just using a counting for loop (without the iterator), or using just the iterator and using iterator subtraction to recover the index:

for (auto it = var.begin(); it != var.end(); ++it) {
    // current position is it - var.begin();
}

And, finally, if you have a C++20-compliant compiler, you could eliminate the iterator entirely and use an enhanced for loop in the following way:

/* Requires C++20 */
for (int i = 0; Foo f: var) {
    /* Do something worthwhile with f. */

    i++;
}

Hope this helps!


You can do it like this:

int i = 0;
for( std::vector<int>::iterator it = v.begin(); it < v.end(); ++it, ++i){}

Tags:

C++

Stl

For Loop