In addition to the problem mentioned in the songyuanyao answer, the code you submitted is undefined. First, it is possible that the vector should be redistributed due to push_back , and then all iterators are invalid and thus increase the undefined loop variable.
See the documentation for push_back :
If the new size () is larger than the capacity (), then all iterators and links (including the past end iterator) are invalid. Otherwise, only the last end iterator is invalid.
I would say that adding to a vector in a range-based for statement is undefined behavior anyway, because the final iterator is always invalid. A range-based copy of the original end() -iterator is stored, and this iterator is invalid after the first push_back . This matches your result as it still points to the original end of the three element vector. However, you should not rely on this behavior.
Unfortunately, I could not find a hard definition of the semantics of the "invalid iterator" in the standard. Β§24.2.1.11 states that invalid iterators can be singular, but only the states that dereference them can be undefined. There is no semantics for comparing them, but taking into account the fact that one implementation for vectors is to use the next memory address following the internal memory, and this address changes when the vector is redistributed, I would say that the cycle is undefined.
source share