Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erase set iterator value and increment iterator

Tags:

c++

set

stl

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?

like image 563
Md. Ikramul Murad Avatar asked Apr 19 '26 12:04

Md. Ikramul Murad


1 Answers

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.

like image 164
NathanOliver Avatar answered Apr 21 '26 03:04

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!