Hi All,

I work on C++, and I am using an number of hash maps in my code. The problem is that, erasing of all the map iterators does not work, I get segmentation faults. If I dont erase the iterators, then everything works fine. I am afraid if I do not erase the iterators after use then memory leak would happen, is that true ?

Also say if there is an iterator to a hash map then what is the difference between these terms -

map.erase(iter->first); and map.erase(iter);

which one shall I chose and why ? and what will happen if I do not erase the iterators.

Thanks.

You aren't erasing the iterator, you are erasing the contents of your map.

An iterator is practically always a locally-constructed variable, so you don't have to worry about destructing it. From your point of view (the programmer) you can consider an iterator the same as a pointer into a container (in this case, the map).

The following two codes are analogous:

char s[] = "Hello world!";
char* p;
for (p = s; *p != '\0'; p++)
  *p = toupper( *p );
string s = "Hello world!";
string::iterator p;
for (p = s.begin(); p != s.end(); p++)
  *p = toupper( *p );

Hope this helps.

If I am not erasing iterator then what is the difference between these two lines ?

map.erase(iter->first);
and
map.erase(iter);

Thanks.

but that is not resulting in a compilation error....I am looking on ur links..
Thanks for help ..

Argh. Sorry, I made a dumb mistake. iter->first is the key, so it is erasing the item with the named key...

This article has been dead for over six months. Start a new discussion instead.