C++ Primer(第5版) 3.6节练习

本文通过C++Primer(第5版)的三个练习题,介绍了三种不同的数组遍历方法:使用范围for循环、下标运算符及指针方式,并展示了如何利用类型别名、auto关键字简化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++ Primer(第5版)练习3.43,不使用类型别名、auto关键字或decltype关键字​

#include <iostream>
using namespace std;

int main()
{
	int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
	// 范围for语句
	for (const int (&row) [4] : ia) {
		for (int col : row)
			cout << col << " ";
		cout << endl;
	}
	cout << endl;
	// 下标运算符
	for (size_t i = 0; i < 3; i++) {
		for (size_t j = 0; j < 4; j++)
			cout << ia[i][j] << " ";
		cout << endl;
	}
	cout << endl;
	// 指针
	for (int (*p) [4] = ia; p != ia + 3; p++) {
		for (int *q = *p; q != *p + 4; q++)
			cout << *q << " ";
		cout << endl;
	}
	cout << endl;

	getchar();
    return 0;
}

​C++ Primer(第5版)练习3.44,使用类型别名来代替循环控制变量的类型

#include <iostream>
using namespace std;

int main()
{
	int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };

	// using int_array = int[4];	// 新标准下类型别名的声明
	typedef int int_array[4];	// 等价的typedef声明

	// 范围for语句
	for (const int_array &row : ia) {
		for (int col : row)
			cout << col << " ";
		cout << endl;
	}
	cout << endl;
	// 下标运算符
	for (size_t i = 0; i < 3; i++) {
		for (size_t j = 0; j < 4; j++)
			cout << ia[i][j] << " ";
		cout << endl;
	}
	cout << endl;
	// 指针
	for (int_array *p = ia; p != ia + 3; p++) {
		for (int *q = *p; q != *p + 4; q++)
			cout << *q << " ";
		cout << endl;
	}

	getchar();
    return 0;
}

C++ Primer(第5版)练习3.45,使用auto关键字

#include <iostream>
using namespace std;

int main()
{
	int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };

	// 范围for语句
	for (const auto &row : ia) {
		for (auto col : row)
			cout << col << " ";
		cout << endl;
	}
	cout << endl;
	// 下标运算符
	for (size_t i = 0; i < 3; i++) {
		for (size_t j = 0; j < 4; j++)
			cout << ia[i][j] << " ";
		cout << endl;
	}
	cout << endl;
	// 指针
	for (auto p = ia; p != ia + 3; p++) {
		for (auto q = *p; q != *p + 4; q++)
			cout << *q << " ";
		cout << endl;
	}

	getchar();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值