Below is my code. I erase the element of which value is 3 and obtain next iterator by erase() function. But when I tried to print its value.It crashed to my surprise. Anyone know the problem??
int main() { std::vector<int> a = {1, 2, 3, 4, 5}; for(vector<int> ::iterator it=a.begin();it!=a.end();it++) { vector<int> ::iterator g; if(*it==3 ) { g=a.erase(it); } cout<<*g<<endl; }
itis wrong. And the use ofgin this is rather pointless, and the dereference dump of*gin all cases where*it == 3is false immediately invokes undefined behavior. the increment step of theforloop should be empty, the statement within theifcondition should beit = a.erase(it);, and anelse { ++it; }should follow theifblock. That, assuming I understand what you're trying to do here. There are dozens of duplicates of this encounter on this site. I'll try and find one to close this out.