少し思い切って言うと、OPの最初のステートメントは、コンマ演算子の動作方法が原因でコンパイルされません。OPはiterator
完全なタイプ名の代わりに省略形を使用していたと確信していますが、それは問題ではありません。
for (iterator it= aVector.begin(), int index= 0; it!= aVector.end(); ++it, ++index)
コンマ演算子は、2つの式を区切る(そして2番目の式の結果を返す)か、宣言内の変数を区切るために使用されます。for引数の最初の引数はどちらの形式でもかまいません。したがって、これらが異なる構文であるという事実がわかりにくくなります。
#include <vector>
#include <iostream>
int main()
{
std::vector<int> aVector = {1,1,2,3,5,8,13};
// option 1. Both loop variables declared outside the for statement, initialized inside the for statement
int index1 = 0;
decltype(aVector.begin()) it1;
for (it1 = aVector.begin(), index1=0; it1!= aVector.end(); ++it1, ++index1)
{
std::cout << "[" << index1 << "]=" << *it1 << std::endl;
}
// option 2. The index variable declared and initialized outside, the iterator declared and initialized inside
int index2=0;
for (auto it2 = aVector.begin(); it2!= aVector.end(); ++it2, ++index2)
{
std::cout << "[" << index2 << "]=" << *it2 << std::endl;
}
#if 0
// option3 (the OP's version) won't compile. The comma operator doesn't allow two declarations.
for (auto it3 = aVector.begin(), int index3=0 ; it3!= aVector.end(); ++it3, ++index3)
{
std::cout << "[" << index3 << "]=" << *it3 << std::endl;
}
#endif
}