为什么自动类型不能与c++语句中的其他内置类型共存

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

本文关键字:其他 内置 置类型 语句 类型 不能 c++ 为什么      更新时间:2023-10-16

看下面的代码:

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

无法成功编译。当我使用其他内置类型而不是auto时,这将是ok的。例如:

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

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