项目符号列表 c++

List of bullets c++

本文关键字:c++ 列表 符号 项目      更新时间:2023-10-16

我正在编写 Directx9 和 c++ 的魂斗罗游戏请帮我了解项目符号列表

我正在尝试下面的代码,但它是错误的:矢量交互器不兼容

 std::vector<Bullet*> bullets
if (mKeyboard->IsKeyPress(DIK_X))
{
    Bullet* toShoot = new Bullet(noneType, _position.x, _position.y, RIGHT);
    toShoot->Init();
    bullets.push_back(toShoot);
}

更新功能:

 std::vector<Bullet*>::iterator it = bullets.begin();

 while ((it) != bullets.end())
  {
    (*it)->Update(gameTime, c);
    if ((*it)->IsLive() == false)
    {
        bullets.erase(it++);
    }
  }

渲染功能

std::vector<Bullet*>::iterator it = bullets.begin();
while (it != bullets.end())
{
    if ((*it)->IsLive())
    {
        (*it++)->Render(gr, cx, cy);
    }
}

你不能只递增传递给erase(…)的迭代器。请改为执行以下操作:

if (!(*it)->IsLive()) {
  it = bullets.erase(it);
} else {
  ++it;
}

您的渲染函数有一个不同的错误。它卡在第一个非活动项目符号上,因为增量在 if 块内。这是for(…)通常比while(…)更可取的原因之一:

for (auto it = bullets.begin(); it != bullets.end(); ++it) {
    if (…) {
        …
    }
}

实际上,更新功能也应该更改,但省略++it

Update 函数中,在迭代向量时调用erase。 问题是,如果在从矢量中删除的同时在循环中使用it迭代器,则可能会失效。

另一种方法是使用erase/remove_if成语:

#include <algorithm>
//...
bullets.erase(std::remove_if(bullets.begin(), bullets.end(), 
              [&](Bullet& b) { b.Update(gameTime, c); return !b.IsLive(); }),
              bullets.end());

调用算法函数remove_if()以确定erase()函数将删除哪些项目符号。 请注意,lambda 包含您用于确定是否应删除项目符号的逻辑。