-1

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; } 
1
  • The setup for managing it is wrong. And the use of g in this is rather pointless, and the dereference dump of *g in all cases where *it == 3 is false immediately invokes undefined behavior. the increment step of the for loop should be empty, the statement within the if condition should be it = a.erase(it);, and an else { ++it; } should follow the if block. 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. Commented Mar 12, 2021 at 7:43

1 Answer 1

3

Why my program crash after dereference of returned iterator of erase() function?

After you have indirected through that iterator and inserted it into cout, you proceed to increment it which is (potentially) invalid, and then also compare it to another iterator and later indirect through it. This results in undefined behaviour.

Even before that, in case *it != 3, you indirect through g which is uninitialised, which results in undefined behaviour.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.