Jump to content
  • Advertisement
Sign in to follow this  
Buzz1982

checking if iterator is null?

This topic is 4159 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!