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.

The first should result in a compilation error and the second deletes the element at *iter.

You need to find a good reference. The two I tend to use are:
http://www.cppreference.com/ (very simple and curt)
http://www.cplusplus.com/reference/ (nicely detailed when the first won't do)

So a map::erase() reads thus and thus.

Hope this helps.

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...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.