遍历二维数组的三类方法(C++)

遍历二维数组的三种方式

1.下标法

for (int i = 0; i < row; i++) {
		for (int j = 0; j < column; j++) {
			cout << array[i][j]<<'\t';
		}
		cout << endl;
}

2.指针法

for (int(*prow)[column] = array; prow < array + row; prow++) {
		for (int *pcolumn = *prow; pcolumn < *prow + column; pcolumn++) {
			cout << *pcolumn << '\t';
		}
		cout << endl;
}

循环中使用的变量类型比较复杂,为了方便阅读我们可以为其定义类型别名:

//通过typedef
typedef int(*poutter)[column];
typedef int(*pinner);
for (poutter p = array; p < array + row; p++) {
	for (pinner q = *p; q < *p + column; q++) {
		cout << *q << '\t';
	}
	cout << endl;
}

//通过using
using poutter = int(*)[column];
using pinner = int*;
for (poutter p = array; p < array + row; p++) {
	for (pinner q = *p; q < *p + column; q++) {
		cout << *q << '\t';
	}
	cout << endl;
}

或者更进一步,将类型推导交给编译器:

for (auto p = array; p < array + row;p++) {
		for (auto q = *p; q < *p + column;q++) {
			cout << *q << '\t';
		}
		cout << endl;
}

C++还为内置数组类型封装了类似于迭代器的东西:

#include<iterator>
for (auto itrow = begin(array); itrow != end(array); itrow++) {
		for (auto itcolumn = begin(*itrow); itcolumn != end(*itrow); itcolumn++) {
			cout << *itcolumn << '\t';
		}
		cout << endl;
}

3.range-based for 循环

for (int (&row)[column] : array) {
		for (int e : row) {
			cout << e << '\t';
		}
		cout << endl;
}

或者由编译器推导类型:

for (auto &row:array) {
		for (auto e:row) {
			cout << e << '\t';
		}
		cout << endl;
}
发布了22 篇原创文章 · 获赞 36 · 访问量 6074

猜你喜欢

转载自blog.csdn.net/cxm2643199642/article/details/104367720