#include
#include
int main() {
std::vector vec;
for (int i = 0; i < 42; ++i) {
vec.push_back(i);
From std::vector::push_back :
If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.
Range-based for loop uses iterators internally. Using push_back may cause these iterators to be invalidated.
Edit : Notice that when y == 22 you are inserting a 65th element into your vector. It's likely the capacity was 64. Many implementations increase capacity by powers of 2 (doubling it each time).