当我在第一个循环中使用 'auto' 时它工作正常,但是使用 'int' 时会出现错误,为什么?

0 c++ vector c++11 c++14

如您所见,我的代码运行良好,但我对访问 a 时在第一个循环中使用auto和有疑问:intvector

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<vector<int>> a{{1,2,3},{4,5,6}};
    //why don't work when i use int in the first loop,and why it work when i use auto  
    for(auto n:a)
    {
        for(int b:n)
        {
           cout<<b<<" ";
        }
        cout<<endl;
    }
 }
Run Code Online (Sandbox Code Playgroud)

asm*_*mmo 5

因为在第一个循环(外部循环)中,ntypestd::vector<int>不是 an int。

请注意,这a是一个向量的向量,因此它的元素是向量,而不是整数。当然,其元素的每个元素的元素都是整数。

基于范围的循环可以明确地写为

for(vector<int> n:a)
Run Code Online (Sandbox Code Playgroud)

或者更好

for(vector<int>& n:a)
Run Code Online (Sandbox Code Playgroud)

避免抄袭

或者更好

for(const vector<int>& n:a)//equivalent to for(const auto & n:a)
Run Code Online (Sandbox Code Playgroud)

因为你没有改变它