为什么 auto 类型不能与 for 语句 C++ 中的其他内置类型共存

why auto type cannot coexist with other build-in type in for statement C++

看下面的代码:

vector<int> ivec(10);
for (auto it = ivec.begin(), int i = 0; it != ivec.end(); it++)
{
  //body;
}

无法编译成功。当我使用其他内置类型代替 auto 时就可以了。例如:

for (int i = 0, double d = 1.0; i < d; i++)
 {
   //body
 }

谢谢。

无法编译,因为在 for 循环中声明多个类型是语法错误。

我猜你想在跟踪索引的同时进行迭代?

这里有多种方法之一:

#include <iostream>
#include <vector>
#include <utility>

using namespace std;

auto main() -> int
{
    vector<int> ivec { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
    for (auto p = make_pair(ivec.begin(), 0) ; 
         p.first != ivec.end() ; 
         ++p.first, ++p.second)
    {
        cout << "index is " << p.second;
        cout << " value is " << *(p.first) << endl;
    }

    return 0;
}

预期输出:

index is 0 value is 10
index is 1 value is 9
index is 2 value is 8
index is 3 value is 7
index is 4 value is 6
index is 5 value is 5
index is 6 value is 4
index is 7 value is 3
index is 8 value is 2
index is 9 value is 1

(注意使用预增量来防止不必要的迭代器副本)