C++ Primer(第五版) 3.5.4--3.6节练习

本文详细解答了C++ Primer第五版中3.5.4至3.6节的若干练习题,包括理解指针的值为内存地址、范围for与普通for的不同使用方式以及类型别名和auto关键字的应用场景。

3.37    输出结果是hello,每个字符占一行。

3.38    指针的值只是所指对象的内存地址,将两个地址值相加没有意义。

3.39    

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main()
{
	string s1 = "s1";
	string s2 = "s2";
	const char c1[] = "s3";
	const char c2[] = "s4";

	if (s1 > s2)
		cout << "s1 > s2" << endl;
	else 
		cout << "s1 < s2" << endl;

	auto r = strcmp(c1, c2);
	if (r > 0)
		cout << "s3 > s4" << endl;
	else if (r < 0)
		cout << "s3 < s4" << endl;
	else
		cout << "s3 = s4" << endl;

	return 0;
	
}

3.40   

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
	const char c1[] = "hello";
	const char c2[] = " world";
	
	char c3[40];
	strcpy(c3, c1);
	strcat(c3, c2);

	for (auto i  = 0; i <= strlen(c3); ++i)
		cout << c3[i];
	cout << endl;

	return 0;
}

3.41

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	int arr[] = {1, 2, 3, 4, 5};
	vector<int> ivec(begin(arr), end(arr));

	for (auto i : ivec)
		cout << i << " ";
	cout << endl;

	return 0;
}

3.42    

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	vector<int> ivec = {1, 2, 3, 4, 5};
	int arr[5];

	for (auto i = 0; i < ivec.size(); ++i)
		arr[i] = ivec[i];

	for (auto i : arr)
		cout << i << " ";
	cout << endl;
	
	return 0;
}

3.43    用范围for:

#include <iostream>

using namespace std;

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

int main()
{
	for (int (&row)[4] : ia) {
		for (int col : row) {
			cout << col << " ";
		}
		cout << endl;
	}

	return 0;
}

    普通for用下标:

for (int row = 0; row != 3; ++row) {
		for (int col = 0; col != 4; ++col)
			cout << ia[row][col] << " ";
		cout << endl;
	}

普通for用指针:

	for (int (*rp)[4] = ia; rp != ia + 3; ++rp) {
		for (int *cp = *rp; cp != *rp + 4; ++cp)
			cout << *cp << " ";
		cout << endl;
	}

3.44    用类型别名:

using int_arr = int[4];

int main()
{
	for (int_arr &row : ia) {
		for (int col : row) {
			cout << col << " ";
		}
		cout << endl;
	}

	return 0;
}

用类型别名和指针:

for (int_arr *rp = ia; rp != ia + 3; ++rp) {
		for (int *cp = *rp; cp != *rp + 4; ++cp)
			cout << *cp << " ";
		cout << endl;
	}

3.45    用auto:

for (auto &row : ia) {
		for (auto col : row) {
			cout << col << " ";
		}
		cout << endl;
	}

用auto,普通for,下标:

for (auto row = 0; row != 3; ++row) {
		for (auto col = 0; col != 4; ++col)
			cout << ia[row][col] << " ";
		cout << endl;
	}

用auto,普通for,指针:

for (auto rp = ia; rp != ia + 3; ++rp) {
		for (auto cp = *rp; cp != *rp + 4; ++cp)
			cout << *cp << " ";
		cout << endl;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值