c++ remove_if删除以下所有元素

C++ remove_if removes all following elements

本文关键字:元素 删除 remove if c++      更新时间:2023-10-16

我正在尝试用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查询的状态。