checking if iterator is null?

Started by
2 comments, last by Buzz1982 16 years, 10 months ago
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
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.
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.
thanks, it solved the problem.

This topic is closed to new replies.

Advertisement