我有一张带卡片的矢量,我需要找到卡片并将其删除。我尝试了下面的代码但是我收到了错误: binary' ==':找不到运算符,它采用类型为' Card' 的左手操作数
代码对我有意义。你能给我一些如何使其有效的提示吗?谢谢!
void Player::RemoveCardFromPackage(const Card& cardToBeRemoved)
{
std::vector<Card>::iterator position = std::find(CadrVector.begin(), CadrVector.end(), cardToBeRemoved);
if (position != CadrVector.end())
{
CadrVector.erase(position);
}
}
答案 0 :(得分:3)
您希望std::find()
如何比较自定义类型CadrVector
的两个元素?当其中两个元素被认为是相等的而不是时?你必须定义它。
所以要么将比较器传递给std::find()
的第四个参数,要么重载你类型的==
运算符。
答案 1 :(得分:2)
您可以使用自定义比较功能尝试find_if
:
#include <iostream>
#include <algorithm>
#include <vector>
class Card
{
int c;
public:
Card(int c): c(c) {}
int GetC() const { return c; }
};
std::vector<Card> CardVector;
class Player
{
public:
void RemoveCardFromPackage(const Card& cardToBeRemoved);
};
void Player::RemoveCardFromPackage(const Card& cardToBeRemoved)
{
auto found = std::find_if(CardVector.begin(), CardVector.end(), [&cardToBeRemoved](Card const &card)
{
return cardToBeRemoved.GetC() == card.GetC();
});
if (found != CardVector.end())
{
CardVector.erase(found);
}
}
int main()
{
Player p;
Card c1(1);
CardVector.push_back(c1);
Card c2(2);
CardVector.push_back(c2);
Card c3(3);
CardVector.push_back(c3);
std::cout << "Before:\n";
for (size_t i = 0; i < CardVector.size(); ++i)
std::cout << "Card C: " << CardVector[i].GetC() << " ";
p.RemoveCardFromPackage(c2);
std::cout << "\n\nAfter:\n";
for (size_t i = 0; i < CardVector.size(); ++i)
std::cout << "Card C: " << CardVector[i].GetC() << " ";
return 0;
}
打印:
Before:
Card C: 1 Card C: 2 Card C: 3
After:
Card C: 1 Card C: 3