Erasing map elements in a while loop

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
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++);
}
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);
}
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
In the reference section I found that map & set do not return an iterator.

This was changed in C++11
FYI, the best way to clear a map is to call clear().
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?
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).
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.
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.
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
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.