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

标签 c++ for-loop auto

<分区>

看下面的代码:

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

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

关于c++ - 为什么 auto 类型不能与 for 语句 C++ 中的其他内置类型共存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33261325/

相关文章:

python - 当在应用中也计算前一个值时,Pandas 中是否可以使用 dataframe.apply 中的前一行值?

c++ - 新的 auto 关键字指针会自行删除吗?

c++ - 为什么 decltype 用于尾随返回类型?

c++ - 编译器减少 std::copy 到 memcpy (memmove) 的条件是什么

c++ - con.txt 和 C++

python |使用 One-Liner 在每次迭代的列表中插入两个项目

c++ - 模板类中 auto 的不完整类使用

c# - #define 的成本是多少?

C++ vector 删除崩溃程序

python - 如何将每一行对与前一列相关联?