C++ Primer 第四版特别版 P83 习题3.13
C++ Primer 第四版特别版 P83 习题3.13
读一组整数到vector对象,计算并输出每对相邻元素的和。如果读入元素个数为奇数,则提示用户最后一个元素没有求和,并输出其值。
#include <iostream>#include <vector>using namespace std;int main(){ cout << "Enter integers:" << endl; vector<int> ivec; int val; while (cin >> val) { ivec.push_back(val); } if (ivec.empty()) { cout << "No data?!" << endl; return -1; } else { vector<int>::size_type ix; for (ix = 0; ix < ivec.size() - 1; ix += 2) { cout << "element" << ix + 1 << " + " << "element" << ix + 2 << " = " << ivec[ix] + ivec[ix + 1] << endl; } if (--ivec.size() == ix) //这一行提示错误:lvalue required as decrement operand cout << "最后一个元素没有求和,其值为 " << ivec[ix] << endl; } return 0;}