更新:
这个讨论比我预期的更深入,所以当这个问题突然出现在我脑海中时,我正在使用我实际正在处理的代码来更新它。在我的 C++ 入门课程中,决定谁是井字游戏的赢家需要 8 到 16 行代码。
注意:这旨在与课程保持一致,
注 2: token 是 x 或 o 或 ' ' 的字符
这是一个优化问题。如果这是重复,我很抱歉,但我无法在其他地方找到答案。
基本上,它归结为以下代码是否会更好地循环:
char CheckForWinner() {
//returns the token of the player that satisfies one of the winning requirements
if (Square[0][0] == Square[0][1] && Square[0][0] == Square[0][2] ) { //If all three tokens in the first row are the same
return Square[0][0]; //Return the token
} else if (Square[1][0] == Square[1][1] && Square[1][0] == Square[1][2] ) { //Check the next row
return Square[1][0]; //Return the token
} else if (Square[2][0] == Square[2][1] && Square[2][0] == Square[2][2] ) {
return Square[2][0];
} else if (Square[0][0] == Square[1][0] && Square[0][0] == Square[2][0] ) { //If no rows satisfy conditions, check columns
return Square[0][0]; //Return the token
} else if (Square[0][1] == Square[1][1] && Square[0][1] == Square[2][1] ) {
return Square[0][1];
} else if (Square[0][2] == Square[1][2] && Square[0][2] == Square[2][2] ) {
return Square[0][2];
} else if (Square[0][0] == Square[1][1] && Square[0][0] == Square[2][2] ) { //finally, check diagonals
return Square[0][0];
} else if (Square[0][2] == Square[1][1] && Square[0][2] == Square[2][0] ) {
return Square[0][2];
}
return ' ';
}
这对他们只需键入 100 行 cout 行的系统是否或多或少会造成负担?
我很好奇,因为看起来我们不仅执行了 100 行计算,而且还为内存分配了一个新变量,并强制计算机处理 100 个数学方程并输出数据。
我可以理解编译器可能会提供某种程度的优化,但我有兴趣在更一般的层面上了解。首先,我使用 VisualStudio 2012 或 MingGW (g++) 进行编译。