C++ primer 5 3.6节练习:遍历二维数组的各种形式

#include <iostream>  
#include <cstring>
#include <vector>
using namespace std;


int main()
{	
	size_t cnt = 0;
	const int row = 5, col = 6;
	int a[row][col] = { 0 };

	using int_arry = int[col];//类型别名声明
	/**初始化二维数组a**/
	for (auto &r:a)
		for (auto &c : r)
		{
			c = cnt;
			cnt++;
		}
	/*****版本1,范围for遍历二维数组*****/
	cout << "版本1,范围for:" << endl;
	for (int (&p)[col]:a)//注意:此时的p是一个col个整数的数组的引用,即类型不再是int &p而是int (&p)[5]
	{
		for (int &q:p)
			cout << q << " ";
		cout << endl;
	}
	cout << endl;

	/*****版本2,普通for遍历二维数组*****/
	cout << "版本2,下标运算符遍历:" << endl;
	for (size_t p1 = 0; p1 != row; ++p1)
	{
		for (size_t q1 = 0; q1 != col; ++q1)
			cout << a[p1][q1] << " ";
		cout << endl;
	}
	cout << endl;

	/*****版本3,普通for遍历二维数组*****/
	cout << "版本3,指针遍历:" << endl;
	for (int(*p2)[col] = begin(a); p2 != end(a); p2++)//同样,如同版本1 p2是一个指向有col个整数的数组的指针,即类型是int (*p2)[col]
	{
		for (int *q2 = begin(*p2); q2 != end(*p2); q2++)//对于q2则是一个整数指针,因为每个col个整数的数组中的元素为整数
			cout << *q2 << " ";
		cout << endl;
	}
	cout << endl;

	/*版本4,用类型别名遍历改写版本1,版本3*/
	cout << "版本4,类型别名改写版本1:" << endl;
	for (int_arry &p3 : a)//即int_arry &p3 = int (&p3)[col]
	{
		for (int &q3 : p3)
			cout << q3 << " ";
		cout << endl;
	}
	cout << endl;

	/*版本4,用类型别名遍历改写版本3*/
	cout << "版本5,类型别名改写版本3:" << endl;
	for (int_arry *p4 = begin(a); p4 != end(a); p4++)
	{
		for (int *q4 = begin(*p4); q4 != end(*p4); q4++)
			cout << *q4 << " ";
		cout << endl;
	}
	cout << endl;
	system("pause");
	return 0;
}

结果如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值