#include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char *argv[]) {
vector<int> v{0, 1, 2, 3, 4};
for (auto it = v.begin(), e = v.end(); it != e; ++it) {
const int x = *it;
cout << x << endl;
v.push_back(x);
}
return 0;
}
I am new to c++, I have this program and I think the answer should be 0 1 2 3 4. But actually output is 0 0 2 3 4. I want to know the reason thx.
You've invoked undefined behavior. The moment v
resizes (which likely happens on the first push_back
), all existing iterators are rendered invalid. You can't rely on any particular behavior in that case. The only reason you didn't end up with a semi-infinite loop is that you cached the end
iterator too, and the two invalid iterators pointed to the old memory and kinda sorta worked as expected (but might not under a different compiler, OS, runtime library, phase of the moon, etc.).