0
点赞
收藏
分享

微信扫一扫

C++ 使用范围 for 遍历多维数组用引用

int main()
{
    constexpr size_t rowCnt = 3, colCnt = 4;
    int ia[rowCnt][colCnt];

    // 使用 for 循环遍历初始赋值
    for (size_t i = 0; i != rowCnt; ++i)
    {
        for (size_t j = 0; j != colCnt; ++j)
        {
            ia[i][j] = i * colCnt + j;
        }
    }

    // 使用范围 for 遍历
    for (const auto &row : ia)
    {
        for (auto col : row)
        {
            cout << col << endl;
        }
    }

    // 使用范围 for 修改
    for (auto &row : ia)
    {
        for (auto &col : row)
        {
            ++col;
        }
    }

    // 输出看一下
    cout << '\n';
    for (const auto &row : ia)
    {
        for (auto col : row)
        {
            cout << col << endl;
        }
    }

    // 下面这种形式不行
    /*
    for (auto row : ia) // row 被解析成 int * 类型了
        for (auto col : row)  // 编译报错
    */

    return EXIT_SUCCESS;
}

输出:

0
1
2
3
4
5
6
7
8
9
10
11

1
2
3
4
5
6
7
8
9
10
11
12

因为row不是引用类型,所以编译器初始化 row 时会自动将这些数组形式的元素(和其他类型的数组一样)转换成指向该数组内首元素的指针。

Note:

要使用范围 for 语句处理多维数组,除了最内层的循环外,其他所有循环的控制变量都应该引用类型


《C++ Primer》 P114



举报

相关推荐

0 条评论