If I erase all 5 elements of a vector during first iteration of a standard for loop
std::vector<int> test {1, 2, 3, 4, 5}; for(int i = 0; i < test.size(); i++) { if(test[i] == 1) test.erase(test.begin(), test.end()); std::cout << i << " "; } it will iterate only once and the std::cout output will be '0'.
However if I do the same thing using a range-based loop, it will iterate 5 times, despite all elements of vector being erased.
int i = 0; for (auto &a: test) { if (a==1) test.erase(test.begin(), test.end()); std::cout << i << " "; i++; } And the std::cout output will be '0 1 2 3 4'.
Where does such different behaviour come from, when using those two types of loops?