【问题标题】:When I use 'auto' in the first loop it works fine, but with 'int' it gives an error, why?当我在第一个循环中使用“auto”时,它工作正常,但使用“int”时会出错,为什么?
【发布时间】:2020-07-08 04:30:52
【问题描述】:

如您所见,我的代码运行良好,但我对在访问vector 时在第一个循环中使用autoint 存在疑问:

#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;
    }
 }

【问题讨论】:

  • auto from vector 被替换为 int 但来自 vector> cat 的 auto 被替换为 vector
  • 出于同样的原因int x = a[0]; 是一个错误。

标签: c++ c++11 vector c++14


【解决方案1】:

因为在第一个循环(外部循环)中,n 类型是 std::vector&lt;int&gt; 而不是 int

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

基于范围的循环可以显式写为

for(vector<int> n:a)

甚至更好

for(vector<int>& n:a)

避免复制

甚至更好

for(const vector<int>& n:a)//equivalent to for(const auto & n:a)

因为你没有改变它

【讨论】:

  • 出于类似原因,auto 版本最好写成for (const auto&amp; n : a)
猜你喜欢
  • 2021-06-19
  • 2019-11-07
  • 1970-01-01
  • 2017-04-16
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
相关资源
最近更新 更多