通过循环擦除向量中的数据导致断点
Erasing data in vector via loop causing breakpoints
我有一个包含 class 个对象(子弹)的向量,它在大多数情况下都有效。但是,一旦我尝试删除项目符号,它就会循环回去,然后导致断点。 "basic game.exe has triggered a breakpoint."我试过前后迭代,但总是卡住。
我正在使用 SFML,对象是具有位置、旋转和大小的矩形。
for (it = bullets.end(); it != bullets.begin(); it--)
{
it->draw(game);
it->move();
if (it->bullet.getPosition().x > 800)
{
bullets.erase(it);
}
}
我是编码菜鸟,所以如果您需要其他信息,请尝试提供。
当您在向量上调用 erase() 时,迭代器将变得无效。
相反,考虑试试这个:
for (auto it = bullets.begin(); it != bullets.end();)
{
it->draw(game);
it->move();
if (it->bullet.getPosition().x > 800)
{
it = bullets.erase(it);
}
else
{
it++;
}
}
您可以使用
修复循环
for (auto& bullet : bullets) {
bullet.draw(game);
bullet.move();
}
bullets.erase(std::remove_if(bullets.begin(), bullets.end(),
[](const auto& bullet) {
return bullet.getPosition().x > 800;
}),
bullets.end());
我有一个包含 class 个对象(子弹)的向量,它在大多数情况下都有效。但是,一旦我尝试删除项目符号,它就会循环回去,然后导致断点。 "basic game.exe has triggered a breakpoint."我试过前后迭代,但总是卡住。
我正在使用 SFML,对象是具有位置、旋转和大小的矩形。
for (it = bullets.end(); it != bullets.begin(); it--)
{
it->draw(game);
it->move();
if (it->bullet.getPosition().x > 800)
{
bullets.erase(it);
}
}
我是编码菜鸟,所以如果您需要其他信息,请尝试提供。
当您在向量上调用 erase() 时,迭代器将变得无效。 相反,考虑试试这个:
for (auto it = bullets.begin(); it != bullets.end();)
{
it->draw(game);
it->move();
if (it->bullet.getPosition().x > 800)
{
it = bullets.erase(it);
}
else
{
it++;
}
}
您可以使用
修复循环for (auto& bullet : bullets) {
bullet.draw(game);
bullet.move();
}
bullets.erase(std::remove_if(bullets.begin(), bullets.end(),
[](const auto& bullet) {
return bullet.getPosition().x > 800;
}),
bullets.end());