C++ Primer 第四版特别版 P83 习题3.13
C++ Primer 第四版特别版 P83 习题3.13
读一组整数到vector对象,计算并输出每对相邻元素的和。如果读入元素个数为奇数,则提示用户最后一个元素没有求和,并输出其值。
- C/C++ code
#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;}为什么会出错呢?
我尝试把这一行改为 if (ix == ivec.size()-1),编译没问题,但是当读入元素个数为奇数时,却并不输出最后那句话和最后一个元素的值,这又是为什么呢?
我在for循环结束以后加了两条语句输出ix和ivec.size()的值:
cout << "ix = " << ix << endl;
cout << "ivec.size() = " << ivec.size() << endl;
如果输入的数字依次为1,2,3,4,5的话,这里ix=4,ivec.size()=5,ix确实是等于ivec.size()-1的啊?!
为什么不输出最后的语句呢???
[解决办法]
1.先说说--ivec.size() 出错!原因 ivec.size() 返回一个值 例如5 给--5 这个能和法吗? --需要的是左值!
2.1 2 3 4 5 ctrl+z 这样子试试你的输入格式不正确!