【问题标题】:using a range for loop without using the auto keyword c++使用范围 for 循环而不使用 auto 关键字 c++
【发布时间】:2017-12-29 23:01:42
【问题描述】:

对于这个分配,我应该使用一个范围来打印出 ia 中的元素,而不使用 auto 关键字。基本上,这项任务是试图帮助我们理解多维数组。我知道代码中发生了什么,但我一直遇到一些错误。语法有问题,我想不通。

int ia[3][4] = {{0,1,2,3},{4,5,6,7},{8,9,10,11}};

cout << endl;
for(int &a : ia)
    for(int b : a)
        cout << b << endl;

我不断收到这些错误:

..\src\Sec_3_5_3.cpp:127:15:错误:从 'int*' 到 'int' 的无效转换 [-fpermissive] for(int &a : ia)

..\src\Sec_3_5_3.cpp:127:15: 错误:无法将右值 '(int)((int*)__for_begin)' 绑定到 'int&'

..\src\Sec_3_5_3.cpp:128:15: 错误: 'begin' 未在此范围内声明

..\src\Sec_3_5_3.cpp:128:15:错误:未在此范围内声明“结束”

【问题讨论】:

    标签: c++ arrays for-loop range iteration


    【解决方案1】:

    每个ia[i] 不是int,而是一个由4 个ints 组成的数组。
    为了能够保持大小,您必须使用参考:

    for(int (&a)[4] : ia)
        for(int b : a)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 2021-01-24
      • 2021-05-02
      • 2012-05-19
      相关资源
      最近更新 更多