只需一个函数调用即可输出分数
Outputting the score with only one function call
我正在尝试检查分数并输出谁获胜。黑色>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) );
相关文章:
- 函数调用导致没有输出
- 错误:哈希函数必须可使用键类型的参数进行调用
- 检查函数是否可调用
- 使用类构造函数作为可调用对象
- 基于对函数的参数调用流输出运算符的能力重载函数
- 如何在另一条消息(M1)之前调用带有消息(M2)的lambda函数,但输出要"M2 M1"?
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 函数调用另一个函数会给出错误的输出 C++
- 定义一个函数使用可调用对象作为参数
- 调用合并函数时没有输出
- C++,多次调用时输出不同的函数
- c++oop初学者-在一个函数调用中返回向量中每个创建对象的输出和
- 一个只调用过一次的大函数是否可以内联
- 输出函数调用日志文件
- 在matlab中调用可执行函数,速度比原生matlab代码慢
- 为什么函数调用中的可变数组长度在C中是可能的,而在C++中是不可能的
- 是否有任何标准的Visual Studio 2008插件可用于跟踪/记录C++项目的构造函数和析构函数调用
- 只需一个函数调用即可输出分数
- 用c++调用的第二个构造函数(错误的输出)
- gcc是否会优化对相同变量的重复函数调用,并为每次调用提供相同的输出?