C++ 中用于二维数组的 for-each 循环
for-each-loop in c++ for two dimensional array
我知道我们可以使用以下代码来打印数组中的元素,例如:
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
}
}
相关文章:
- 这个 FOR-IF 循环的解释是什么?
- C++ 中用于二维数组的 for-each 循环
- 简单的 for() 循环基准测试在任何循环绑定下花费相同的时间
- 在 fork() 之后,如何在 for() 循环中继续运行 execve()
- 迭代在包含向量的vor in for for范围循环中迭代
- 计算 fib(n) 的次数称为 FOR EACH n
- 支持自定义 const 本机C++容器类的"for each"
- C++ for-each 语句触发"vector iterators incompatible"断言失败:this->_Getcont() == 0
- 为什么我的矢量中的项目在 C++ 中的 for-each 循环期间不会改变?
- 当循环返回"for each"项的 nullptr 时?
- 基于范围的循环与 for-each 循环有何不同
- C++:从"for each"循环中的映射中删除值
- 正在擦除for(-each)自动循环中的项目
- 将循环转移到C++03 for each
- 在 for-each 循环中使用 'auto' 时是否需要添加'const'?
- C++中的"for each"循环如何知道数组的长度
- 基本c++: for-each循环
- 如何使c++中的for each循环函数与自定义类一起工作
- 如何使用for-each循环来美化析构函数
- for-each 循环生成错误,但 for(it=begin()...在遍历 std::map 包含 unique_ptr 时不会