Md. Ikramul Murad
Md. Ikramul Murad

Reputation: 199

Erase set iterator value and increment iterator

I have seen a programmer write this.

auto it=myset.lower_bound(x);
myset.erase(it++);

How can I get the next iterating pointer through post increment operator if I already have deleted the current iterating pointer value?

Upvotes: 10

Views: 2146

Answers (1)

NathanOliver
NathanOliver

Reputation: 180500

When you call

myset.erase(it++);

A couple things happen. First it++ gets evaluated before it is passed to the function. When you evaluate it++ the result of that is it and that is what gets passed to the function. So your function gets the value of it but the value of it in the call site is what it is after being incremented. That means when erase erases the element the iterator points to it is erasing what the old iterator points to that you no longer have. This is a completely valid and safe way to erase an element from a set.

As an alternative, starting in C++11, erase returns the next valid iterator so you could use

it = myset.erase(it);

and it will have the same effect.

Upvotes: 20

Related Questions