3

I am confusing with the "'iter' was not declared in this scope" error.

#include <vector>

using std::vector;

int main()
{
    vector<int> vec{1,2,3,4,5,6};
    for(std::size_t i,vector<int>::iterator iter=vec.begin();iter!=vec.end();++i,++iter)
    {
        //do something
    }
}
Li Kui
  • 499
  • 4
  • 14

3 Answers3

13

Just like you can do

int a = 10, b = 20;

A for loop's first section does the same thing. Since you can't do

int a = 10, double b = 20;

The same thing applies to the for loop.

Technically you can have two different types as you can declare an type and a pointer to that same type on the same line like

int i = 0, *b = nullptr;

And that is also valid to do in a for loop.

NathanOliver
  • 150,499
  • 26
  • 240
  • 331
6

In C++17, there is a feature known as a structured binding declaration that allows you do to do this. For example:

for (auto [iter, i] = std::tuple{vec.begin(), 0u}; iter != vec.end(); ++iter, ++i) 
{
    /* ... */
}

While this nearly matches the syntax you were hoping for, the tuple part is not very readable, so I would just declare one of the variables outside of the loop.

Live Example

Arnav Borborah
  • 9,956
  • 4
  • 32
  • 69
5

It can, but both variables need to be the same type.

The common thing to do, when you need to maintain an index as well as an iterator is to write

{ // extra scoping block
    std::size_t i = 0; // indeed, you need to initialise i
    for(vector<int>::iterator iter = vec.begin(); iter != vec.end(); ++i,++iter)
    {
        // do something
    }
}
Bathsheba
  • 220,365
  • 33
  • 331
  • 451