every blog every motto: You will never know unless you try
0. Preface
Simply record several methods of traversing two-dimensional arrays
1. Text
1.1 Method 1:
#include<iostream>
using namespace std;
// 定义常量
const int ROW = 3; // 数组的行数
const int COLUMN = 5; // 数组的列数
void test123()
{
// 生成数组
int arr[3][5] = {
{
0,1,1,0,1 },
{
0,0,1,0,1 },
{
0,0,1,0,1 }
};
int *p;
p = arr[0];
for (int row=0; row < ROW; row++)
{
for (int column=0; column < COLUMN ;column++)
{
cout << arr[i][j] << " "; // 关键部分
}
cout << endl;
}
}
int main()
{
test123();
system("pause");
}
1.2 Method Two: Pointer
1.2.1 Write separately
#include<iostream>
using namespace std;
// 定义常量
const int ROW = 3; // 数组的行数
const int COLUMN = 5; // 数组的列数
void t2()
{
// 生成数组
int arr[3][5] = {
{
0,1,1,0,1 },
{
0,0,1,0,1 },
{
0,0,1,0,1 }
};
int *p;
p = arr[0];
for (int row=0; row < ROW; row++)
{
for (int column=0; column < COLUMN ;column++)
{
cout << *p << " "; // 关键部分
p++; // 关键部分
}
cout << endl;
}
}
int main()
{
t2();
system("pause");
}
1.2.2 Combined Write
#include<iostream>
using namespace std;
// 定义常量
const int ROW = 3; // 数组的行数
const int COLUMN = 5; // 数组的列数
void t2()
{
// 生成数组
int arr[3][5] = {
{
0,1,1,0,1 },
{
0,0,1,0,1 },
{
0,0,1,0,1 }
};
int *p;
p = arr[0];
for (int row=0; row < ROW; row++)
{
for (int column=0; column < COLUMN ;column++)
{
cout << *p++ << " "; // 关键部分
}
cout << endl;
}
}
int main()
{
t2();
system("pause");
}
1.3 Method Three: Pointer
#include<iostream>
using namespace std;
// 定义常量
const int ROW = 3; // 数组的行数
const int COLUMN = 5; // 数组的列数
void test123()
{
// 生成数组
int arr[3][5] = {
{
0,1,1,0,1 },
{
0,0,1,0,1 },
{
0,0,1,0,1 }
};
int *p;
p = arr[0];
for (int row=0; row < ROW; row++)
{
for (int column=0; column < COLUMN ;column++)
{
cout << p[row*COLUMN+column] << " "; // 关键部分
}
cout << endl;
}
}
int main()
{
test123();
system("pause");
}