有点悬疑,由于逗号运算符的工作方式,OP 的第一条语句无法编译。我确定 OP 只是使用简写iterator
而不是完整的类型名,但这不是问题:
for (iterator it= aVector.begin(), int index= 0; it!= aVector.end(); ++it, ++index)
逗号运算符要么分隔两个表达式(并返回第二个表达式的结果),要么用于分隔声明中的变量。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
}