使用 'this' 关键字从向量中删除元素

Remove element from vector using 'this' keyword

相当简单的问题。

我有一个 Bullet 对象,当子弹与一个对象碰撞时,它会在某一时刻被破坏并从 Bullets 向量中移除。

每个 Bullet 对象都有对 vector/list 个项目符号的引用。

发生这种情况时,如何使用 Bullet class 中的 this 关键字将其删除?

void collide(){
    //error C2678: binary '==': no operator found which takes a left-hand operand of type 'Bullet'
    //(or there is no acceptable conversion)
    bullets->erase(std::remove(bullets->begin(), bullets->end(), *this), bullets->end());
}

是的,该代码给了我一个奇怪的错误。 我需要知道如何在不使用 while/for 循环并仅使用向量函数迭代项目符号向量的情况下做到这一点。显然,当前方法不起作用,因为它会喷出代码中注释的错误。

我也试过使用 find() 而不是 remove(),同样的错误。

您需要在项目符号 class 中实现 == 运算符。 如果你想根据它的内存地址删除一个项目,你可以简单地遍历向量并天真地找到元素:

    for (Bullet& bullet : bullets){
        if (&bullet == this){
          bullets.erase(bullet);
            break;
         }
     }

您需要获取指向要删除的对象的迭代器。你可以通过第一个和当前对象之间的差异来获取它:

bullets->erase(bullets->begin() + (this - &bullets.front()));

请注意,这将破坏您当前正在执行其方法的对象,即您之后无法访问该成员的任何对象。

试试这个:

std::remove_if( bullets.begin(), bullets.end(), 
   [this] (const Bullet& s) {
      if (&s == this)
          return true;
      return false;
   }
);