C++ 什么可以用来替换代码中的循环和if语句?
我实现了战舰游戏。这里我有一个函数,它检查游戏场的正确性C++ 什么可以用来替换代码中的循环和if语句?,c++,algorithm,loops,C++,Algorithm,Loops,我实现了战舰游戏。这里我有一个函数,它检查游戏场的正确性 bool Model::checkMyField() const { // Check field for correct ship placement return ( shipNum(1) == 4 && shipNum(2) == 3 && shipNum(3) == 2 && shipNum(4) ==
bool Model::checkMyField() const
{
// Check field for correct ship placement
return (
shipNum(1) == 4 &&
shipNum(2) == 3 &&
shipNum(3) == 2 &&
shipNum(4) == 1
);
}
int Model::shipNum( int size ) const
{
int shipNumber = 0;
for( int i = 0; i < 10; i++ )
for( int j = 0; j < 10; j++ )
if( isShip(size, i, j) )
shipNumber++;
return shipNumber;
}
bool Model::isShip( int size, int x, int y ) const
{
// left field !clear
if( x > 0 && myField->getCell(x - 1, y) != CL_CLEAR )
return false;
// up field !clear
if( y > 0 && myField->getCell(x, y - 1) != CL_CLEAR )
return false;
// no ship here
if( myField->getCell(x, y) == CL_CLEAR )
return false;
int tmp = x;
int num = 0;
// checking in right direction
while( myField->getCell(tmp, y) != CL_CLEAR && tmp < 10 )
{
tmp++;
num++;
}
if( num == size )
{
if( myField->getCell(x, y + 1) != CL_CLEAR )
return false;
return true;
}
tmp = y;
num = 0;
// checking in down direction
while( myField->getCell(x, tmp) != CL_CLEAR && tmp < 10 )
{
tmp++;
num++;
}
if( num == size )
{
if( myField->getCell(x + 1, y) != CL_CLEAR )
return false;
return true;
}
return false;
}
和小lambda在一起,但我不知道怎么做。你能解释一下怎么做,并给我一个1个lambda的例子,让我理解它并为其他ifs创建自己的lambda吗?或者建议我还可以使用什么。以避免双重循环
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
这里更简单的方法是重用现有的容器,例如std::array
或std::vector
constexpr std::size boardSize = 10;
constexpr std::array<Pos, boardSize * boardSize> compute_positions()
{
std::array<Pos, boardSize * boardSize> res{};
std::size_t i = 0;
for (std::size_t x = 0; x != boardSize; ++x) {
for (std::size_t y = 0; y != boardSize; ++y) {
res[i++] = {x, y};
}
}
return res;
}
constexpr std::array<Pos, boardSize * boardSize> positions = compute_positions();
如果它是唯一一个有双循环的地方,那么它就没有真正的用处;)
对于if
部分:
if (x > 0 && myField->getCell(x - 1, y) != CL_CLEAR)
return false;
无法移除,但可以通过包围特殊单元板来移除绑定支票
因此,您可以使用12x12板,而不是10x10板。具有适当值的额外单元格(CL\u CLEAR
似乎适合显示的代码,但新值可能更好)必须调整索引,而不是
[0-9]
,可能的值现在是[1-10]。
但应用+1或-1仍然有效
if (myField->getCell(x, y + 1) != CL_CLEAR) // you forgot bound checking
return false;
return true;
可以简化为
return myField->getCell(x, y + 1) == CL_CLEAR;
int Model::shipNum( int size ) const
{
return std::count_if(positions.begin(),
positions.end(),
[&](auto& pos){ return isShip(size, pos.x, pos.y); });
}
if (x > 0 && myField->getCell(x - 1, y) != CL_CLEAR)
return false;
if (myField->getCell(x, y + 1) != CL_CLEAR) // you forgot bound checking
return false;
return true;
return myField->getCell(x, y + 1) == CL_CLEAR;