只需一个函数调用即可输出分数

Outputting the score with only one function call

本文关键字:函数调用 可输出 一个      更新时间:2023-10-16

我正在尝试检查分数并输出谁获胜。黑色>0,白色<0,并且平局为==0。如果GetValue(board)==0而不再次调用我的函数或使用其他变量,我应该怎么做?

GetValue(board) > 0 ? cout << "Black wins" : cout << "White wins"; 

为什么不想使用变量?如果你这样做,你可以使用一个复合三元运算符:

int val = GetValue(board);
cout << val == 0 ? "Tie" : (val < 0 ? "White wins" : "Black wins");

编辑:但这不是一行,是吗?REAL的一行代码,由lambda函数提供
它还假设GetValue返回一个int。为了简洁起见,它需要一个using namespace std

cout << vector<string>({"White wins", "Tie", "Black Wins"})[([](int x){return(0<x)-(x<0)+1;}(GetValue(board)))];

(也不要实际使用)

如果您想通过一个函数调用输出分数,可以执行以下操作:

cout << msg[ GetValue(board) + 1] << endl;

其中:

msg[0] = "White Wins";
msg[1] = "Tie";
msg[2] = "Black Wins";

这假设GetValue返回-1、0或1;

std::string win_message(int const &x)
{
    if ( x == 0 ) return "Tie";
    if ( x < 0 ) return "Black wins";
    return "White wins";
}
// ...
    cout << win_message( GetValue(board) );