C++ 数组遍历的两种方式:
#include <iostream> using namespace std; int main()
{
// 一维数组
int fibonacci[] = {, , , , }; // 使用索引遍历
// 求数组长度:sizeof(array)/sizeof(array[0])
cout << "Traverse By Index: ";
for (int i = ; i < sizeof(fibonacci)/sizeof(fibonacci[]); i++)
{
cout << fibonacci[i] << " ";
}
cout << endl; // 使用指针遍历
// 取数组的(第一个元素)地址:int* p = array
// 求数组最后一个元素的地址:&array[sizeof(array)/sizeof(array[0])-1]
cout << "Traverse By Pointer: ";
for (int* p = fibonacci; p <= &fibonacci[sizeof(fibonacci)/sizeof(fibonacci[])-]; p++)
{
cout << *p << " ";
}
cout << endl; // 二维数组
int matrix[][] = {{, , }, {, , }, {, , }}; // 使用索引遍历
// 求一维数组长度:sizeof(array)/sizeof(array[0])
// 求二维数组长度:sizeof(array[0])/sizeof(array[0][0])
cout << "Traverse By Index: " << endl;
for (int i = ; i < sizeof(matrix)/sizeof(matrix[]); ++i)
{
if (!i == )
{
cout << "| ";
}
for (int j = ; j < sizeof(matrix[])/sizeof(matrix[][]); ++j)
{
cout << matrix[i][j] << " ";
}
}
cout << endl; // 使用指针遍历
// 求二维数组首元素地址:int* p = &(matrix[0][0])
// 求二维数组尾元素地址:&matrix[sizeof(matrix)/sizeof(matrix[0])-1][sizeof(matrix[0])/sizeof(matrix[0][0])]
int count = ;
cout << "Traverse By Pointer: " << endl;
for (int* p = &(matrix[][]); p < &matrix[sizeof(matrix)/sizeof(matrix[])-][sizeof(matrix[])/sizeof(matrix[][])]; ++p)
{
if (count == (sizeof(matrix[])/sizeof(matrix[][])))
{
cout << "| ";
count = ;
}
cout << *p << " ";
count++;
}
cout << endl; return ;
}