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;
}
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 )
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.