我有一个游戏,我向一个物体射击子弹,然后我删除了被子弹击中的物体以及屏幕外的子弹。
例如:
std::vector<object> object_list;
for(size_t i = 0; i < object_list.size(); i++)
{
if(object_list[i].hit())
{
object_list.erase(object_list.begin() + i);
}
else
object_list[i].draw();
}
Run Code Online (Sandbox Code Playgroud)
The problem with this is that when i remove an object, the size of the vector decreases so when it check the conditions, it fails and i get an error such as " vector subscript out of range." I could just choose not to render the asteroid by rendering those that haven't been hit, but the problem with that is that the no. of objects increases when hit(splits up) so eventually the program is going to get slower. I've used a similar concept for the off screen bullets but I can't find a way around it. I'm looking for a solution to this or better way of removing elements.
Both object and bullet are classes.
您应该将 for 循环分为两部分:
object_list.erase(std::remove_if(object_list.begin(),
object_list.end(), [](auto&& item) { return item.hit(); }),
object_list.end());
Run Code Online (Sandbox Code Playgroud)
std::for_each(object_list.begin(), object_list.end(), [](auto&& item) { item.draw(); });
Run Code Online (Sandbox Code Playgroud)
它更安全,更具可读性。