【发布时间】:2016-10-15 00:22:43
【问题描述】:
我正在尝试使用 c++ 和 SFML2 创建一个小游戏,但当我尝试擦除敌人对象时,我遇到了这个问题。
我有一个“Mover”类型的“僵尸”向量,当我尝试使用这个 lambda 函数从向量中删除一个特定的僵尸时:
zombies.erase(remove_if(zombies.begin(), zombies.end(), [](Mover& m) {return m.isDead(); }), zombies.end());
它会删除向量的所有后续元素(如果我有一个 10 个元素的向量并且我尝试删除第 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);
}
问题可能出在这里吗?也许我在初始化时做错了(下面的代码),但我不确定这种初始化是否适用于我拥有的其他类型的实体(例如 es 弹丸)。
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;
}
同样的问题
【问题讨论】:
-
这个 sn-p 看起来不错,可能显示
Mover类型 -
你真的需要展示更多的代码。
-
您是否自己为
Mover编写了复制(和/或移动)构造函数?如果有,它是什么样子的? -
operator=是赋值运算符,而不是复制构造函数 -
那时我没有复制或移动构造函数。我应该写吗? (无论如何我都在这样做,我只是想知道我的问题是否与此有关)
标签: c++ vector lambda iterator sfml