std::cout 内的三元条件运算符

Ternary conditional operator inside std::cout

这是我的代码:

std::cout << "The contaner is " << (!container)?"not":; "empty";

这显然行不通,但我希望现在思路清晰了。我想打印 "The container is empty",如果 bool containerfalse,则在 "empty" 之前添加 "not"

我想知道这是否可能,或者我是否必须按照以下方式写一些东西:

if(container) std::cout ...;
else std::cout ...; 

尝试...<< (!container ? "not" : "") << "empty".

当所有其他方法都失败时,只需使用 if 语句:

std::cout << "The contaner is ";
if (!container)
    std::cout << "not ";
std::cout<< "empty";

就我个人而言,我更喜欢这个而不是使用条件运算符,因为它更容易阅读。当您要显示的内容类型不同时,这也适用。条件运算符要求将两种情况都转换为通用类型,因此 !container ? "not" : 1 之类的内容将不起作用。

你快到了。三元运算符将需要 else 结果,您可以使用空字符串 "",然后,由于优先级问题,您需要用括号封装表达式:

std::cout << "The contaner is " <<  (!container ? "not" : "") << "empty";

可以在非空的情况下添加空字符串。

std::cout << "The container is " << (!empty ? "not ": "") << "empty";

或者调低一点聪明度,我个人觉得这样更易读,

std::cout << "The container is " << (empty ? "empty": "not empty");