C++多維數組

多維數組也稱為C++中的矩形數組。 它可以是二維或三維的。 數據以表格形式(行*列)存儲,也稱為矩陣。

C++多維數組示例

下麵來看看一個C++中的多維數組的簡單例子,它聲明,初始化和遍曆二維數組。

#include <iostream>
using namespace std;
int main()
{
    int test[3][3];  //declaration of 2D array
    test[0][0]=5;  //initialization
    test[0][1]=10;
    test[1][1]=15;
    test[1][2]=20;
    test[2][0]=30;
    test[2][2]=10;
    //traversal
    for(int i = 0; i < 3; ++i)
    {
        for(int j = 0; j < 3; ++j)
        {
            cout<< test[i][j]<<" ";
        }
        cout<<"\n"; //new line at each row
    }
    return 0;
}

執行以上代碼,得到以下結果 -

5 10 0
0 15 20
30 0 10

C++多維數組示例:同時聲明並初始化

下麵來看看一個在聲明時初始化數組的多維數組的簡單例子。

#include <iostream>
using namespace std;
int main()
{
    int test[3][3] =
    {
        {2, 5, 5},
        {4, 0, 3},
        {9, 1, 8}  };  //declaration and initialization
    //traversal
    for(int i = 0; i < 3; ++i)
    {
        for(int j = 0; j < 3; ++j)
        {
            cout<< test[i][j]<<" ";
        }
        cout<<"\n"; //new line at each row
    }
    return 0;
}

執行以上代碼,得到以下結果 -

2 5 5
4 0 3
9 1 8

上一篇: C++將數組傳遞到函數 下一篇: C++指針