[英]C++ vector erase at specific index doesn't get it to work
我的问题是,当我尝试擦除向量中的秘密对象时,它将删除该对象之前的所有对象。
我已经在Bullet课堂上做到了,这和它有关系吗?
Bullet operator=(Bullet);
Bullet Bullet::operator=(Bullet b) {
Bullet newBullet(NULL, NULL);
return(newBullet);
}
如果我没有这个我会得到
错误C2582:“子弹”中没有“运算符=”功能
在这里,我定义了子弹向量的每个元素:
if (p_shoot) {
bullets.insert(bullets.begin(), Bullet(p_getHitboxX(), p_getHitboxY() + (p_getHitboxH() / 2)));
p_shoot = false;
}
这是发生的代码:
if (!bullets.empty()) {
for (unsigned int i = 0;i < bullets.size();) {
if (bullets.at(i).bullet_collisionCheck(rect)) {
bullets.erase(bullets.begin() + i);
}
else i++;
}
}
我不明白为什么它要删除要删除的索引中特定Bullet对象之前的所有Bullet对象。 就像它删除了bullet.begin()和i之间的所有对象一样。
假设子弹包含3个Bullet对象,第一个子弹相撞,使bullet_collisionCheck返回true,这意味着索引为0,但随后它先擦除了bullets [2],然后擦除了bullets [1],最后擦除了我想要的bullets [0]。首先擦除。
我一直在进行实验以查看发生了什么,因此我编写了这段代码以查看发生了什么:
bullets.push_back(Bullet(100, 100));
bullets.push_back(Bullet(200, 200));
bullets.push_back(Bullet(300, 300));
bullets.push_back(Bullet(400, 400));
bullets.push_back(Bullet(500, 500));
bullets.erase(bullets.begin() + 3);
运行此代码时,应删除Bullet(400,400),但要删除最后一个Bullet(500,500)。 我将值更改为1,这意味着它应该删除Bullet(200,200),但仍然删除最后一个Bullet(500,500)。 到底是怎么回事?
请帮忙。
我找到了解决问题的方法,谢谢大家的帮助。
问题是:
Bullet operator=(Bullet);
Bullet Bullet::operator=(Bullet b) {
Bullet newBullet(NULL, NULL);
return(newBullet);
}
我只需要将其更改为:
void operator=(const Bullet &b);
void Bullet::operator=(const Bullet &b) {
bullet_hitbox.x = b.bullet_hitbox.x;
bullet_hitbox.y = b.bullet_hitbox.y;
}
试试看:仅使用基于迭代器的迭代而不是基于索引的迭代。
if(!bullets.empty())
{
for ( auto it = bullets.begin(); it != bullets.end(); ++it )
{
if ( it->bullet_collisionCheck(rect) )
{
it = bullets.erase( it );
--it;
}
}
}
使用“ bullets.insert(bullets.begin(),...”)添加新对象将在开始时添加新对象,因此,第一个创建的使bullet_collisionCheck返回true的项目符号将是最后一个(bullet [2])。 if (bullets.at(i).bullet_collisionCheck(rect))
引起问题的条件,因为bullets.erase(bullets.begin() + i);
应该可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.