for(it = gameObjects.begin();it!=gameObjects.end();it++){
it->second->update(frameTime);
if(it->second->getSprite()->GetPosition().y > 500){
std::cout << "Removing enemy" << std::endl;
std::map<sf::String,VisibleGameObject*>::iterator itor = Remove(it->second->getName());
if(itor!=gameObjects.end()){
std::cout << "itor doesn't equal" << std::endl;
it=itor;
}else{
std::cout << "itor = end" << std::endl;
it=itor;
}
}
}
一旦 itor = end
被打印出来,它就会出错——“map set iterator not incrementable”。我认为 for 循环应该在它再次递增之前结束,因为 it!=gameObjects.end()
在此之后将为 false。在 else 语句中添加 break
可以解决问题。
为什么没有 break
就不能工作?我假设与检查条件时相比,迭代器递增时与此有关。
最佳答案
您假设正确。迭代器在循环结束时递增,然后检查条件。
因此在打印“itor = end”之后,它会递增到 gameObjects.end()++
这当然是无效的。您可以通过检查循环内的 itor == gameObjects.end()
然后中断来绕过。
编辑:正如评论中所指出的,您最好只是从循环中删除++it,以避免在删除的元素之后跳过该元素。例如:
for( it = gameObjects.begin(); it!=gameObjects.end(); ) {
...
if(it->second->getSprite()->GetPosition().y > 500) {
it = Remove( it->second->getName() );
} else {
++it;
}
}
关于c++ - for 循环在满足条件时不会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9046111/