0

I'm looping through an STL map to delete elements and do some clean up. Unfortunately for me my program crashes on the ++iter line. Am I doing something wrong in how I'm looping over the map?

std::map<string,BoneHierarchy* >::iterator iter = boneMap.begin();
while(iter != boneMap.end()) {
    string playerName = iter->first;
    boneMap[playerName]->clear();
    boneQueue->push(boneMap[playerName]);
    boneMap.erase(iter);
    ++iter;
}
Xavier
  • 8,828
  • 13
  • 64
  • 98

2 Answers2

6

Don't increment the iterator after deleting it (it's been erased, so how can you expect to increment it?). Erase a copy of the iterator with:

boneMap.erase(iter++);

or do

iter = boneMap.erase(iter);

if using C++11.

(See also Removing elements from a C++ map through a for-loop)

Community
  • 1
  • 1
Cornstalks
  • 37,137
  • 18
  • 79
  • 144
3
boneMap.erase(iter);
++iter;                     //incorrect

should be written as:

iter = boneMap.erase(iter); //correct (in C++11)
//no need to increment!

Because map::erase() returns iterator following the erased item.

Nawaz
  • 353,942
  • 115
  • 666
  • 851