I have a simple yet troublesome case of using std::vector in C++. The pop_back method slowly decreases the size of the vector at the same time that it is being iterated in the for each loop. This however goes on with no problems and the size of the vector in the end of the for each loop is 0. How come that the last elements are still able to be accessed while they are not in the vector? (calling push_back on last iteration places the new number on index 0 of the vector)
#include <vector>
int main() {
std::vector<int> v1 = {1,2,3,4,5};
for(int& n : v1){
n++;
std::cout << n << " ";
v1.pop_back();
if(n==6){ v1.push_back(865); }
}
std::cout << v1.size();
return 0;
}
Thank you!