對於許多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/zh-tw/n/187016.html
微信掃一掃
支付寶掃一掃