C++ 数组遍历的两种方式:
#include <iostream> using namespace std; int main() { // 一维数组 int fibonacci[5] = {1, 1, 2, 3, 5}; // 使用索引遍历 // 求数组长度:sizeof(array)/sizeof(array[0]) cout << "Traverse By Index: "; for (int i = 0; i < sizeof(fibonacci)/sizeof(fibonacci[0]); 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[0])-1]; p++) { cout << *p << " "; } cout << endl; // 二维数组 int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 使用索引遍历 // 求一维数组长度:sizeof(array)/sizeof(array[0]) // 求二维数组长度:sizeof(array[0])/sizeof(array[0][0]) cout << "Traverse By Index: " << endl; for (int i = 0; i < sizeof(matrix)/sizeof(matrix[0]); ++i) { if (!i == 0) { cout << "| "; } for (int j = 0; j < sizeof(matrix[0])/sizeof(matrix[0][0]); ++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 = 0; cout << "Traverse By Pointer: " << endl; for (int* p = &(matrix[0][0]); p < &matrix[sizeof(matrix)/sizeof(matrix[0])-1][sizeof(matrix[0])/sizeof(matrix[0][0])]; ++p) { if (count == (sizeof(matrix[0])/sizeof(matrix[0][0]))) { cout << "| "; count = 0; } cout << *p << " "; count++; } cout << endl; return 0; }
原文地址:https://www.cnblogs.com/noonjuan/p/11874791.html
时间: 2024-10-07 19:45:37