C++ primer(第五版) 练习 3.24 个人code

本文提供了一个C++ Primer第五版中练习3.24的解答示例,该练习要求使用迭代器来实现对一组整数进行特定的求和操作,并展示了完整的代码实现及执行结果。

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


C++ primer(第五版) 练习 3.24


题目:请使用迭代器重做3.3.3节的最后一个练习(练习 3.20)。

3.3.3节最后一个练习为:
读入一组整数并把它们存入一个vector对象,将每对相邻整数的和输出出来,改写你的程序,这欠要求先输出第1个和最后1个元素和,接着输出第2个和倒数第2个元素的和,以此类推。


答:

#include <iostream>
#include <vector>

using std::cout;
using std::cin;
using std::vector;
using std::endl;

int main()
{
	int tmp,sum=0;
	vector<int> v1;

	while (cin >> tmp)
	{
		v1.push_back(tmp);
	}

	//以下是相邻两个求和
	cout << "下是相邻两个求和:" << endl << endl;;
	if (v1.size() % 2== 0)
	{
		for (auto it = v1.begin(); it != v1.end(); it += 2)
			cout << *it + *(it + 1) << endl;
	}
	else
	{
		cout << v1[v1.size() - 1] << "不能成对,无法求和,其它能成对的和如下:" << endl<<endl;

		for (auto it = v1.begin(); it != v1.end() - 1; it += 2)
			cout << *it + *(it + 1) << endl;
	}

	//以下是首尾两个求和。
	cout << "以下是首尾两个求和:" << endl << endl;;
	if (v1.size() % 2 == 0)
	{
		for (auto b = v1.begin(), e = v1.end();b!=e; b++)
			cout << *b + *(--e) << endl;
	}
	else
	{
		cout << v1[v1.size() / 2] << "不能成对,无法求和,其它能成对的和如下:" << endl << endl;
		for (vector<int>::iterator b = v1.begin(), e = v1.end(); b!=e-1; b++)
			cout << *b + *(--e) << endl;
	}

	return 0;

}


执行结果图:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值