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;
}
执行结果图: