c++ remove_if删除以下所有元素
C++ remove_if removes all following elements
我正在尝试用c++和SFML2创建一个小游戏,当我试图擦除敌人对象时,我被这个问题卡住了。
我有一个类型为"Mover"的"僵尸"向量,当我试图用这个lambda函数从向量中擦除特定的僵尸时:
zombies.erase(remove_if(zombies.begin(), zombies.end(), [](Mover& m) {return m.isDead(); }), zombies.end());
将擦除vector的所有元素(如果有10个元素的vector,尝试擦除第8个元素,它将擦除第8,9和10个元素)。
我还在学习语言,所以这可能是一个非常愚蠢的错误,但我一直在寻找解决方案很长一段时间了,我还没有找到任何东西,关于lambdas和remove_if函数的样本代码看起来和我的一样。
谢谢你的帮助
——编辑——
这是isDead函数:
bool Mover::isDead() { return hp.isEmpty(); }
检查HP是否小于或等于0。
当我添加新的僵尸时,如下所示:
vector<Mover> zombies;
Mover z;
z.init(Vector2f(100, 100), Animator(120, Vector2f(512, 896), Vector2f(128, 128), texManager.get("zombie"), Vector2i(8, 1)));
z.setMaxSpeed(0.08);
z.setAngularVelocity(0.3);
for (int k = 0; k < 20; k++)
{
z.setPosition(z.getPosition().x + 10, z.getPosition().y + 10);
z.randomAnimation();
zombies.push_back(z);
}
问题可能在这里吗?也许我在init(下面的代码)上做错了什么,但我不确定这种初始化是否适用于我拥有的其他类型的实体(如弹丸)。
void Mover::init(Vector2f _position, Animator _animator)
{
setPosition(_position);
animator = _animator;
size = animator.getSize();
rect.setSize(size);
tex = animator.getTexture();
sprite.setTexture(*tex);
hp.init(15);
}
——编辑——
刚刚添加了复制构造函数:
►发
声明Mover(const Mover& other);
定义Mover::Mover(const Mover& other) : Entity(other)
{
velocity = other.velocity;
acceleration = other.acceleration;
maxSpeed = other.maxSpeed;
maxForce = other.maxForce;
animator = other.animator;
aVelocity = other.aVelocity;
speedModifier = other.speedModifier;
hp = other.hp;
}
►实体声明Entity(const Entity& other);
定义Entity::Entity(const Entity& other) : Transformable(other), Drawable(other)
{
size = other.size;
rect = other.rect;
tex = other.tex;
sprite = other.sprite;
}
同样的问题使用通灵调试,您的Mover
类型无法正确移动isDead
查询的状态。
相关文章:
- C++如何通过用户输入删除列表元素
- 使用函数"remove"删除重复元素
- 如何通过 getter 函数删除矢量的元素?
- 从控制台中删除最后打印的元素
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除列表中的第n个元素
- 从矢量中删除元素后出现隔离错误
- 删除映射和分割错误中的一个过去结束元素
- 如何使用remove_if从矢量中删除元素
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- 从矢量中删除空元素
- 关于比较两个无序数组并删除 a[] 中可以在 b[] 中找到的元素的问题
- 删除指针数组 (C++) 中的元素
- 删除列表 c++ 中的最后 3 个元素
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 为什么通过 vector<reference_wrapper> 的元素删除引用的值<T>不会使向量无效?
- 从std::multiset的第i个元素删除到末尾
- 删除 [] 是否等于每个元素删除.C++
- std::列出元素删除后节点的内存回收