Sign in to follow this  

checking if iterator is null?

This topic is 3850 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I have a situation where i have to check an iterator for null before erasing a std::map element from the map. Following is my code, std::map< Person, Person, ltstr >::iterator iter; std::map< Person, Person, ltstr > mp; mp.clear(); Person personkey = CreatePerson( PARENT, 100, 100 ); Person personval = CreatePerson( PARENT, 200, 200 ); mp.insert( pair< Person, Person >( personkey, personval ) ); iter = mp.find( personkey ); mp.erase( iter ); if( iter != mp.end() ) mp.erase( iter ); The problem i m facing is that when i get to the statement if( iter != mp.end() ) i recieve an assertion saying "map/set iterator incompatable". Please tell me what is the problem and how to solve it. Thanks Bye

Share this post


Link to post
Share on other sites
Quote:
Original post by Buzz1982
Hello,

I have a situation where i have to check an iterator for null before erasing a std::map element from the map. Following is my code,

std::map< Person, Person, ltstr >::iterator iter;
std::map< Person, Person, ltstr > mp;
mp.clear();

Person personkey = CreatePerson( PARENT, 100, 100 );
Person personval = CreatePerson( PARENT, 200, 200 );
mp.insert( pair< Person, Person >( personkey, personval ) );

iter = mp.find( personkey );
mp.erase( iter );

if( iter != mp.end() )
mp.erase( iter );

The problem i m facing is that when i get to the statement if( iter != mp.end() ) i recieve an assertion saying "map/set iterator incompatable". Please tell me what is the problem and how to solve it.

Thanks

Bye


The problem seems to be that you have an erase call before that statement too, so you might be deleting it twice.

Share this post


Link to post
Share on other sites
The call to erase invalidates your iterator. Luckily, erase returns a new, valid iterator. So just replace your call with
iter = mp.erase( iter );
and the assertion should go away.

Share this post


Link to post
Share on other sites

This topic is 3850 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this