Link to home
Start Free TrialLog in
Avatar of BaconU
BaconUFlag for United States of America

asked on

c++; map interator; detecting when a find() returns an invalid iterator

I've got a map<string,string> as part of a class and am writing a function to delete one of the map items, based on the key name. Once I obtain the iterator - through a find() - I tell it to erase it from the map.  Works great if it finds a match.  If it doesn't find a match, VS2005 pops up an errors "debug assertion failed!".  

I've looked online and cannot find anything which dictates how to test an iterator for a NULL/invalid value.  I finally discovered a solution which IMHO seems rather clunky... but it does the job.

if(iter._Ptr->_Isnil) { return; } //  exit method if invalid iterator

I find it difficult to believe this is the proper way to test for an invalid iterator.  Is there a better way?  The full 'delete' method is listed below.

Oh and I suppose I should mention, this is a cross-platform app, so g++ 4.1.2 will also need to be able to compile it.
void deleteItem(string key) {
    map<string,string>::iterator i = this->_Items->find(key);
    if(i._Ptr->_Isnil) { return; }
    this->_Items->erase(i);
  }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of LordOfPorts
LordOfPorts
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wktang83
wktang83


void deleteItem(string key) {
    map<string,string>::iterator i = this->_Items->find(key);
    if(i._Ptr == this->_Items->end()) { return; }
    this->_Items->erase(i);
  }

Open in new window

Avatar of BaconU

ASKER

Ah, yes... I should have known.  I mistakenly assumed that the end() was only to be used in conjunction with begin().  

This is a much nicer solution!  Thanks LordOfPorts!
Avatar of BaconU

ASKER

wktang83, according to my tests, you don't need the ._Ptr when testing again end().