#include
#include
int main() {
std::vector vec;
for (int i = 0; i < 42; ++i) {
vec.push_back(i);
Once you call std::vector::push_back
or most non-const
function for that matter the iterators are invalidated (When the new size exceeds the current capacity of the vector which causes the memory to be re-allocated internally)
You can find some good references on how standard containers or iterators work in general. I hope that gets you started!
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).