C++ Primer(第5版) 【3.4.2节练习】练习题3.24-3.26及答案

练习3.24

请使用迭代器重做3.3.3节的最后一个练习。

题解:

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

int main() {
	int i = 0;
	vector<int> ivec;
	int sum = 0;

	while (cin >> i) {
        ivec.push_back(i);
	}

	//利用迭代器依次输出每对相邻整数的和
	for (auto it = ivec.cbegin(); it != ivec.cend() - 1; ++it) {
		sum = *it + *(it + 1);
		cout << sum << " ";
		sum = 0;
	}
	//改写:利用迭代器依次输出第i个元素和第v.size()-i-1个元素的和
	auto it1 = ivec.cbegin();
	auto it2 = ivec.cend() - 1;
	while(it1 < it2){
		sum = *it1 + *it2;
		cout << sum << " ";
		++it1;
		--it2;
		sum = 0;
	}
	//计算vector容器的长度,类型为带符号整型数
	vector<int>::difference_type len = ivec.cend() - it1; 
	//如果vector容器的长度为奇数,输出中间位置的元素
	if (len % 2 != 0) {
		//指向中间位置的迭代器
		auto mid = ivec.cbegin() + len / 2;
		cout << *mid << endl;
	}
		
	return 0;
	system("pause");
}

在解答本题时,我犯了两个错误:

错误一:迭代器失效问题。任何一种可能改变vector对象容器的操作,都会使该vector对象的迭代器失效。所以,但凡使用了迭代器的循环体,都不要向迭代器所属的容器添加元素

//错误示例:试图在循环体中利用迭代器向vector容器中添加元素	
int i = 0;
	vector<int> ivec;
	int sum = 0;
	//2.将其存入vector对象中
	while (cin >> i) {
		//错误!
		/*for (auto it = ivec.begin(); it != ivec.end(); ++it) {
			*it = i;
		}*/
	}

错误二: 注意区分 *(it + 1)与 *it + 1

  • 对迭代器解引用得到它所指的对象
  • it +n 表示迭代器向前移动n个位置
#include <iostream>
#include <vector>
using namespace std;

int main() {
	vector<int> ivec{ 3,8,6,7 };
	auto it = ivec.begin();
	//*it是指迭代器所指的元素,即首元素3
	//*it + 1 是指迭代器所指的元素的值加1,即3+1=4
	//it + 1 代表迭代器it向前移动一个位置
	//*(it + 1):对其解引用,也即代表第二个元素8
	cout << " *it 的值为:" << *it << endl;
	cout << " *it + 1 的值为:" << *it + 1 << endl;
	cout << " *(it + 1) 的值为:" << *(it + 1) << endl;
	/*
	 *it 的值为:3
	 *it + 1 的值为:4
	 *(it + 1) 的值为:8
	*/
	return 0;
	system("pause");
}

练习3.25

3.3.3节划分分数段的程序是使用下标运算符实现的,请利用迭代器改写该程序实现完全相同的功能。

题解:

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

int main() {
	vector<int> scores(11,0);
	auto beg = scores.begin();
	unsigned grade;
	//利用迭代器统计各分数段的分数数量
	while (cin >> grade) {
		++*(beg + grade / 10);
	}
	for (auto c : scores)
		cout << c << " ";
	return 0;
	system("pause");
}

练习3.26

在100页的二分搜索程序中,为什么用的是 mid = beg + (end - beg) / 2, 而非 mid = (beg + end) / 2 ; ?

题解:

因为迭代器只支持 - 运算,而没有 + 运算。

end - beg 表示两个迭代器之间的距离,该距离的类型为difference_type,是带符号整型数。注意这两个迭代器必须指向同一个容器中的元素或尾元素的下一个位置

mid = beg + (end - beg) / 2;此mid代表指向vector容器中间元素的一个迭代器

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值