Ner*_*awn 1 c++ algorithm for-loop
我是 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 循环:
bool destroyed = true;
auto foundPosition = std::for_each(ships.begin(), ships.end(), ships);
if (foundPosition != ship.isDestroyed()) {
destroyed = false;
}
return destroyed;
Run Code Online (Sandbox Code Playgroud)
除此之外,我猜这是错误的,我的编译器会抛出以下错误:
>------ Build started: Project: CMakeLists, Configuration: Debug ------
[1/3] Building CXX object src\libGameObjects\CMakeFiles\GameObjects.dir\PlayerSea.cpp.obj
FAILED: src/libGameObjects/CMakeFiles/GameObjects.dir/PlayerSea.cpp.obj
C:\PROGRA~2\MICROS~2\2019\PROFES~1\VC\Tools\MSVC\1429~1.300\bin\Hostx64\x64\cl.exe /nologo /TP -I..\..\..\src\libGameObjects -I..\..\..\src\libSea /DWIN32 /D_WINDOWS /GR /EHsc /Zi /Ob0 /Od /RTC1 -MDd /W4 -std:c++17 /showIncludes /Fosrc\libGameObjects\CMakeFiles\GameObjects.dir\PlayerSea.cpp.obj /Fdsrc\libGameObjects\CMakeFiles\GameObjects.dir\GameObjects.pdb /FS -c ..\..\..\src\libGameObjects\PlayerSea.cpp
C:\Users\janbe\Source\Repos\Gruppe_1C4\blatt8\src\libGameObjects\PlayerSea.cpp(135): error C2065: 'ship': undeclared identifier
ninja: build stopped: subcommand failed.
Run Code Online (Sandbox Code Playgroud)
我知道我还是个菜鸟,请多多关照!显然我没有在网上找到我的问题的答案,或者至少我没有找到一个足够简单让我理解的答案。也许有人可以给我一个提示?:)
看起来您想检查是否所有船只都被摧毁,因此您应该使用std::all_of
.
bool destroyed = std::all_of(ships.begin(), ships.end(),
[](const Ship& ship){ return ship.isDestroyed(); });
Run Code Online (Sandbox Code Playgroud)