我有一个填充了自定义类型值的向量,而find()算法抱怨它无法为值比较找到合适的==运算符。我已经像这样实现了它:
bool Ship::operator==(const Ship& source) {
return (_type == source._type &&
_damagedSquares == source._damagedSquares &&
_orientation == source._orientation && _state == source._state);
}
我也试过了这个朋友"方法方法,但也不起作用。 该类本身的结构如下:
class Ship {
private:
ShipType _type;
int _damagedSquares;
ShipOrientation _orientation;
ShipState _state;
public:
Ship();
Ship(ShipType type);
~Ship();
bool operator==(const Ship& source);
};
我在这里做错了什么?
其他信息:
std::vector<Ship> remainingShips;
MultiArray& squares = opponentGridCopy.GetSquares();
for (RowIterator rowIterator = squares.begin(); rowIterator != squares.end();
++rowIterator) {
for (ColumnIterator columnIterator = rowIterator->begin();
columnIterator != rowIterator->end(); ++columnIterator) {
Square* current = &(*columnIterator);
SquareState currentState = current->GetState();
if (currentState != SquareState::Hit)
current->SetState(SquareState::Vacant);
Ship* potentialShip = current->GetOwner();
if (potentialShip != nullptr) {
int damagedSquares = potentialShip->GetDamagedSquares();
if (!damagedSquares) {
current->SetState(SquareState::Populated);
break;
}
if (remainingShips.empty() ||
std::find(remainingShips.begin(), remainingShips.end(),
potentialShip) ==
remainingShips.end()) // should be *potentialShip
remainingShips.push_back(*potentialShip);
}
}
}
return remainingShips;
我将指针作为比较值传递... 简单地解除引用它并且find()现在可以工作。
答案 0 :(得分:5)
像这样声明你的比较运算符:
bool Ship::operator==( const Ship &source ) const
请注意尾随const
。
答案 1 :(得分:1)
Ship* potentialShip = ...
std::find(remainingShips.begin(), remainingShips.end(), potentialShip)
当你执行搜索的向量定义为
时,你试图找到一个指针std::vector<Ship> remainingShips;
您正在将指针与Ship对象进行比较,因此您的比较是错误的
bool Ship::operator==(const Ship& source) // Accepts a Ship reference, not a pointer
要解决此问题,请取消引用指针或更改比较功能。
答案 2 :(得分:1)
您
bool operator==(const Ship& source);
也应该是const,即
bool operator==(const Ship& source) const;
但实际上,我更喜欢使用对称运算符, not 作为成员方法。 考虑:
Class Ship
{
private:
ShipType _type;
int _damagedSquares;
ShipOrientation _orientation;
ShipState _state;
public:
Ship();
Ship(ShipType type);
~Ship();
static bool eq(const Ship& s0, const Ship& s1)
{
return (s0._type == s1._type &&
s0.damagedSquares == s1._damagedSquares &&
s0._orientation == s1._orientation &&
s0._state == s1._state);
}
};
inline bool operator==(const Ship& s0, const Ship& s1)
{
return Ship::eq(s0, s1);
}