对于许多C++程序员来说,循环遍历二维数组是日常开发过程中很基本也很重要的部分。在本篇文章中,我们将介绍C++中的几个不同方式来循环遍历二维数组。
一、使用foreach循环遍历二维数组
使用foreach循环遍历二维数组是C++11新引入的功能。该方法语法简单并且易于阅读,因为你只需要提供要遍历的数组名称即可。在本例中,我们将遍历一个二维数组,该数组存储了学校四个班级的学生成绩。
int scores[4][3] = {
{89, 92, 78},
{85, 88, 82},
{75, 85, 95},
{66, 77, 68},
};
for (auto &row : scores) {
for (auto &col : row) {
std::cout << col << " ";
}
std::cout << std::endl;
}
运行结果如下:
89 92 78 85 88 82 75 85 95 66 77 68
二、使用for循环遍历二维数组
使用for循环来遍历二维数组是一种通用的方法。我们可以使用两个嵌套的循环来访问所有元素。在本例中,我们将创建一个3×3的二维数组,并使用for循环遍历数组中的所有元素。
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
运行结果如下:
1 2 3 4 5 6 7 8 9
三、使用for循环遍历二维数组c语言
对于有经验的C语言程序员,以下是使用for循环遍历二维数组的方法:
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
运行结果如下:
1 2 3 4 5 6 7 8 9
四、使用增强for循环遍历二维数组
增强for循环也可以用于遍历二维数组,但需要使用指向数组行的指针。在本例中,我们将遍历一个存储了九张牌的三个堆栈的数组。
int stacks[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
for (int i = 0; i < 3; i++) {
int* row_pointer = stacks[i];
for (auto &col : row) {
std::cout << *row_pointer << " ";
row_pointer++;
}
std::cout << std::endl;
}
运行结果如下:
1 2 3 4 5 6 7 8 9
五、使用uibot循环遍历二维数组
uibot foreach循环是开源库uibot中的一部分,可用于遍历二维数组并对所有元素执行操作:
#include "uibot/foreach.h"
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
ui::foreach(arr, [&](int& elem, size_t i, size_t j) {
std::cout << elem << " ";
});
运行结果如下:
1 2 3 4 5 6 7 8 9
六、使用vuefor循环二维数组遍历
vuefor循环是在Vue.js中使用的一种特殊语法,可用于遍历数组并生成HTML元素。在C++中,我们可以使用vuefor循环来执行类似的操作。在本例中,我们将使用vuefor循环遍历一个存储了五个人职业的二维数组。
int careers[5][2] = {
{"John", "Developer"},
{"Mary", "Designer"},
{"Bob", "Architect"},
{"Alice", "Engineer"},
{"Karen", "Manager"}
};std::cout << "";
for(auto& row : careers) {
std::cout << "";
for(auto& column : row) {
std::cout << column << " ";
}
std::cout << "
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/187016.html
微信扫一扫
支付宝扫一扫