【发布时间】:2014-09-02 16:56:13
【问题描述】:
我有一个填充了自定义类型值的向量,而 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() 现在就可以工作了。
【问题讨论】:
-
能否请您出示您的容器并
std::find呼叫它? -
您在使用
std::vector<const Ship>吗?上面的代码没问题 -
@Venom 你能显示完整的错误信息吗?
标签: c++ vector operator-overloading