我是 C++ 新手,我面临以下问题:
我在一个函数中有以下 for 循环:
bool PlayerSea::allShipsDestroyed() const
{
bool destroyed = true;
for (auto const & ship : ships) {
if (!ship.isDestroyed()) {
destroyed = false;
}
}
return destroyed;
}
Run Code Online (Sandbox Code Playgroud)
该函数检查每艘船(每个玩家有 3 艘)是否被摧毁,方法是遍历向量并将“destroyed”设置为 false(如果一艘船尚未被摧毁)。这是通过调用“isDestroyed()”函数来完成的:
bool Ship::isDestroyed() const
{
for (unsigned int i = 0; i < size; ++i) {
Coordinates coordinates = (orientation == Sea::Orientation::X) ? Coordinates(x + i, y) : Coordinates(x, y + i);
if (!wasHitAt(coordinates)) {
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
现在这是我尝试用算法完成的循环替换上面的 for …