项目符号列表 c++
List of bullets c++
我正在编写 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 包含您用于确定是否应删除项目符号的逻辑。
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何维护资源管理器项目视图中当前可见的项目列表
- 在卡萨布兰卡形成编码参数的列表
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题