考虑以下代码:
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char **argv) {
vector<int> v = { 1 };
auto it = v.begin();
cout << ++(*it) << " " << v[0] << " " << endl;
cout << v[0] << endl;
return EXIT_SUCCESS;
}
编译并运行时,此代码会产生以下控制台输出:
2 1
2
鉴于 ++(*it)
递增第一个 vector 值,我希望得到以下输出:
2 2
2
为什么增量没有反射(reflect)在 v[0]
的第一个 cout
语句中?
最佳答案
原因是:
cout<<++(*it);
正在打印下一个值 2
但 v 的原始值仅在该行之后增加:
cout<<++(*it)<<" "<<v[0]<<" "; // v[0] is still `1`
现在值 v[0]
递增,结果为 2
cout<< v[0]<<" ";
您可以在 cout
之前递增
++(*it);
cout<<*it<<" "<<v[0]<<" ";
现在输出是一样的。
关于c++ - 预增量运算符的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33326794/