如果项目被 bool 值设置为不活动,当我尝试从 vector 中删除项目时出现错误。我试过在网上搜索,但没有找到任何相关信息。我试图找到不同的方法来删除 vector 中索引 x 上的元素并找到函数:vector.erase(vector.begin() + index)
因此,当我尝试在我的 for 循环中使用它时,我得到了指向删除函数行的访问冲突读取位置。
错误所在的循环代码:
if (!player.getBullets().empty())
{
for (int x = 0; x < player.getBullets().size(); x++)
{
//Check for projectiles whos status is dead.
if (!player.getBullets()[x]->getAlive())
{
//Erase the element at position x.
player.getBullets().erase(player.getBullets().begin() + x);
}
}
}
最佳答案
不要重新发明轮子,尤其是那些可以在水下和墙壁上移动的真正困难的轮子。使用现成的:
#include <algorithm>
player.getBullets().erase(
std::remove_if(player.getBullets().begin(),
player.getBullets().end(),
[](Projectile * p) -> bool { return !p->getAlive(); }),
player.getBullets().end());
(我假设 Bullet
与 decltype(player.getBullets())::value_type
相同,即子弹容器的元素类型。调整适合。)
关于尝试从 vector 中删除时,C++ 访问冲突读取位置 0x003AE000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20729101/