簡體   English   中英

C++ 從向量中刪除 object?

[英]C++ Remove object from vector?

我想從播放器 class 內部名為“movelist”的向量中刪除 class Attack的 object。 我嘗試使用並收到此錯誤:

error: no match for 'operator==' (operand types are 'Attack' and 'const Attack')

有什么建議么?

void Player::del_attack(Attack a1)
{
   Attack to_rmv=a1;
   movelist.erase(std::remove(movelist.begin(), movelist.end(), to_rmv), movelist.end());
}

我有

#include <algorithm>
#include <vector>

問題是您沒有為Attack class 定義operator== 如果您考慮一下,這是必要的。 要從向量中刪除等於to_rmv的元素,算法需要知道如何測試兩個Attack對象是否相等。

最簡單的答案是為Attack定義operator== ,例如:

// return true if x equals y, false otherwise
bool operator==(const Attack& x, const Attack& y)
{
    // your code goes here
}

您可能需要將此運算符設為Attack class 的friend

std::remove()使用operator==將元素與您要刪除的值進行比較。 如果沒有為您的 class 定義它,那么您應該會遇到這樣的錯誤。

Attack添加這樣的重載應該就足夠了。 例如,對Attack使用簡單的struct

struct Attack {
    int attackId;
    int strength;
};

bool operator==(Attack const& a, Attack const& b) {
   return a.attackId == b.attackId && 
          a.strength == b.strength; 
}

編譯器資源管理器示例: https://godbolt.org/z/8dhrab

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM