Hey guys,
I was working with vectors in C++ and encountered a weird confusing moment while erasing elements from the vector using vector::erase(). I'm attaching a code snippet below, please run it on your local IDE or leetcode playground and let me know your findings.
int main() {
vector<int> abc;
abc.push_back(1);
abc.push_back(2);
abc.push_back(3);
for(int i=0;i<abc.size();i++){
//simply printing the vectors
cout<<abc[i]<<" ";
}
abc.erase(abc.begin());
abc.erase(abc.begin());
abc.erase(abc.begin());
//erased all three elements
cout<<abc.size(); // prints 0
cout<<*abc.begin(); // prints 3
cout<<abc[0]; // prints 3
}The outputs for the last couple lines were very surprising and I wasn't able to figure out the reason for it. If all the elements were erased from the vector ( supported by the fact that the vector size is being printed 0), then how come I'm able to print abc[0] or for that matter even abc[3] which is simply out of allowed index. I'm assuming this is somehow related to pointers or the internal implementation of vectors in c++.
Can someone take the time to explain this? or share a detailed documentation of the internal working of vector::erase(). I wasn't able to extract an understandable version of the same from the depths of the world wide web which I accessed :D
Thanks in advance!
Have a nice day ahead!