【问题标题】:for-each-loop in c++ for two dimensional arrayc++中的for-each循环用于二维数组
【发布时间】:2018-07-07 13:08:49
【问题描述】:

我知道我们可以使用下面的代码来打印数组中的元素,例如:

int a[] = {1,2,3,4,5};
for (int el : a) {
    cout << el << endl;
}

但是如果我们的数组有两个或多个维度呢? 应该如何修改 for 循环以打印更高维数组? 例如:

int b[2][3] = {{1,2,3},{3,4,5}};

谢谢你:)

【问题讨论】:

  • 您需要哪种语言的代码?
  • 我在标题里写的是C++

标签: c++ arrays for-loop syntax


【解决方案1】:

怎么样:

int b[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
for (auto& outer : b)
{
    for (auto& inner : outer)
    {
        std::cout << inner << std::endl;
    }
}

【讨论】:

  • 您能解释一下为什么在这里使用“auto”吗?当我使用“int”时,它只显示内存地址,但使用自动时,它可以工作!!
  • outer 循环中,auto&amp; 是必需的,这样数组就不会衰减为指针。如果您尝试在外循环中使用int,您应该会收到编译错误。在内部循环中,您可以使用int,它应该没问题。见Range based for
【解决方案2】:

基于范围的 for 循环: 下面的简单示例展示了如何使用 基于范围的 for 循环打印 2d 数组

unsigned int arr[2][3] = { {1,2,3}, {4,5,6} }; // 2 rows, 3 columns
for (const auto& row: arr)  // & - copy by reference; const - protect overwrite; 
{
    for (const auto& col : row)
    {
        std::cout << col << " "; // 1 2 3 4 5 6
    }
}

同样,基于范围的循环用于二维向量

vector<vector<int>> matrix { {1,2,3}, {4,5,6} }; // 2 rows, 3 columns

for (const auto& row : matrix)  // & - copy by reference; const - protect overwrite; 
{
    for (const auto& col : row)
    {
        std::cout << col << " "; // 1 2 3 4 5 6
    }
}

【讨论】:

    猜你喜欢
    • 2012-11-15
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多