Erasing map elements in a while loop

Dec 13, 2011 at 9:25am
I have a map with following signature.
 
map<const char*, int, Comparator> map_Keys; //Comparator is defined elsewhere 


I need to clear the map after the use of it. Does following is valid for that?

1
2
3
4
5
6
7
8
9
map<const char*, int, Comparator>::iterator ite = map_Keys.begin();

while ( ite != map_Keys.end() )
{
    delete [] ite->first;
    ite->first = NULL;

    map_Keys.erase(ite); //I'm not sure does this advances the ite for next element
}





Last edited on Dec 13, 2011 at 9:26am
Dec 13, 2011 at 10:07am
No it will not advances, You have to post increment the iterator explicitly.

1
2
3
4
5
6
7
8
9
map<const char*, int, Comparator>::iterator ite = map_Keys.begin();

while ( ite != map_Keys.end() )
{
    delete [] ite->first;
    ite->first = NULL;

    map_Keys.erase(ite++);
}
Dec 13, 2011 at 10:14am
erase returns an iterator to the element after so you can write
1
2
3
4
5
6
7
8
map<const char*, int, Comparator>::iterator ite = map_Keys.begin();

while ( ite != map_Keys.end() )
{
    delete [] ite->first;

    ite = map_Keys.erase(ite);
}
Dec 13, 2011 at 10:22am
Thanks. So what is the best way to implement the clearing of map?

1
2
3
4
5
 map_Keys.erase(ite++);

or

ite = map_Keys.erase(ite);


Does erasing will return next element as vectors & deque?

In the reference section I found that map & set do not return an iterator. But vector & deque does return an iterator on erase.
Last edited on Dec 13, 2011 at 10:29am
Dec 13, 2011 at 10:58am
In the reference section I found that map & set do not return an iterator.

This was changed in C++11
Dec 13, 2011 at 11:58am
FYI, the best way to clear a map is to call clear().
Dec 13, 2011 at 2:24pm
Thanks Peter. I'm not using the C++11 yet. I would expect ite = map_Keys.erase(ite); will work.

Anyway map.clear() will free the char buffers I created on heap?
Dec 13, 2011 at 2:38pm
no clear() will not call delete[].

If the keys are strings why not use std::string instead? If it's just some char data array why not use std::vector? That way you don't need use a custom comparator (unless you have special needs).
Dec 13, 2011 at 4:54pm
Right, I missed the fact that you wanted to delete the pointers and then clear the map. That is a valid approach--to loop once to delete and then call clear.

However, using std::string is what I would do.
Dec 14, 2011 at 1:37am
Yes, I did the correct way of clearing the char keys of the map (in the very first code). Char keys are used to gain more speed.

Thanks for the help.
Dec 14, 2011 at 3:29am
char keys are used to gain more speed

More speed compared to what, lookup in a map with std::string keys? That does not sound plausible. Do you have a test case?
Last edited on Dec 14, 2011 at 3:29am
Dec 14, 2011 at 8:39am
No, I don't use std::string throughout my program. Hence I don't want to keep it as strings in map and avoiding string creations.
Topic archived. No new replies allowed.