3.24 题目:读入一组整数并把他们存入一个vector对象,用迭代器 将每对相邻整数的和输出出来
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vInt;
int iVal;
cout << "请输入一组数字:" << endl;
while (cin >> iVal)
vInt.push_back(iVal);
if (vInt.cbegin() == vInt.cend())
{
cout << "没有任何元素" << endl;
return -1;
}
cout << "相邻两项的和依次是:" << endl;
// 利用auto推断it的类型
for (auto it = vInt.cbegin(); it != vInt.cend() - 1; it++)
{
// 求相邻两项的和
cout << (*it + *(++it)) << " ";
// 每行输出5个数字
if ((it - vInt.cbegin() + 1) % 10 == 0)
cout << endl;
}
// 如果元素数是奇数,单独处理最后一个元素
if (vInt.size() % 2 != 0)
cout << *(vInt.cend() - 1);
system("pause");
return 0;
}
当输入元素个数为偶数时,出现如下错误:
程序可以正常输出但是报错can't dereference out of range vector iterator
当把 18行 it !=vInt.cend()-1 改为 it<vInt.cend()-1 后,不论输入 奇数偶数个元素,都可以正常输出并且不报错