C++ 中用于二维数组的 for-each 循环

for-each-loop in c++ for two dimensional array

本文关键字:for-each 循环 二维数组 用于 C++      更新时间:2023-10-16

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

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

谢谢:)

怎么样:

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

基于范围的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
}
}

类似地,2d 矢量基于范围的循环

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