我可以在 C++ 中将 int 与 boolean 相乘吗?
Can I multiply an int with a boolean in C++?
我的 GUI 中有一个显示图表的小部件。如果我有多个图表,GUI 上的矩形中会显示一个图例。
我有一个 QStringlist (legendText)
,其中包含图例的文本。如果不需要图例,legendText
将为空。如果有图例,legendText
将包含文本。
为了找到图例周围矩形的高度,我想执行以下操作:
int height = 10;
QStringList legendText;
...
height = height * (legendText->size() > 0);
...
将 int
与 boolean
相乘是个好主意/好风格吗?我会 运行 遇到问题吗?
完全符合标准 (§4.5/6):
A prvalue of type bool
can be converted to a prvalue of type int
, with
false
becoming zero and true
becoming one.
但是,我建议使用 isEmpty
而不是将 size
与零进行比较 height = height * (!legendText->isEmpty());
或者按照其他答案的建议使用条件运算符(但仍然使用 isEmpty
而不是 .size() > 0
)
您可以使用条件(三元)运算符:
height = ( legendText->size() >0 ) ? height : 0 ;
这在技术上很好,如果有点不清楚。
bool
将 提升 为 int
,因此结果是明确的。但是,查看该代码我不会立即了解您要实现的语义。
我会简单地写这样的东西:
height = legendText->isEmpty() ? 0 : height;
这让你的意图更加清晰。
也许是这个?
if(legendText->isEmpty())
{
height = 0;
}
或
int height = legendText->isEmpty() ? 0 : 10;
有些人可能会发现以下信息很有用(在每个时钟周期都很重要的高性能程序中应考虑以下代码,这里的目的是展示替代技术,我不会在这种特定情况下使用它)。
如果您需要没有分支的快速代码,您可以使用按位运算符实现与布尔值的 int 乘法。
bool b = true;
int number = 10;
number = b*number;
可以优化为:
number = (-b & number);
如果 b
是 true
,则 -b
是 -1
,并且所有位都设置为 1
。否则所有位都是 0
.
布尔运算 NOT (!b
) 可以通过 b
与 1
(b^1
).
异或来实现
因此,在您的情况下,我们得到以下表达式:
height = (-(legendText->isEmpty()^1) & height);
我的 GUI 中有一个显示图表的小部件。如果我有多个图表,GUI 上的矩形中会显示一个图例。
我有一个 QStringlist (legendText)
,其中包含图例的文本。如果不需要图例,legendText
将为空。如果有图例,legendText
将包含文本。
为了找到图例周围矩形的高度,我想执行以下操作:
int height = 10;
QStringList legendText;
...
height = height * (legendText->size() > 0);
...
将 int
与 boolean
相乘是个好主意/好风格吗?我会 运行 遇到问题吗?
完全符合标准 (§4.5/6):
A prvalue of type
bool
can be converted to a prvalue of typeint
, withfalse
becoming zero andtrue
becoming one.
但是,我建议使用 isEmpty
而不是将 size
与零进行比较 height = height * (!legendText->isEmpty());
或者按照其他答案的建议使用条件运算符(但仍然使用 isEmpty
而不是 .size() > 0
)
您可以使用条件(三元)运算符:
height = ( legendText->size() >0 ) ? height : 0 ;
这在技术上很好,如果有点不清楚。
bool
将 提升 为 int
,因此结果是明确的。但是,查看该代码我不会立即了解您要实现的语义。
我会简单地写这样的东西:
height = legendText->isEmpty() ? 0 : height;
这让你的意图更加清晰。
也许是这个?
if(legendText->isEmpty())
{
height = 0;
}
或
int height = legendText->isEmpty() ? 0 : 10;
有些人可能会发现以下信息很有用(在每个时钟周期都很重要的高性能程序中应考虑以下代码,这里的目的是展示替代技术,我不会在这种特定情况下使用它)。
如果您需要没有分支的快速代码,您可以使用按位运算符实现与布尔值的 int 乘法。
bool b = true;
int number = 10;
number = b*number;
可以优化为:
number = (-b & number);
如果 b
是 true
,则 -b
是 -1
,并且所有位都设置为 1
。否则所有位都是 0
.
布尔运算 NOT (!b
) 可以通过 b
与 1
(b^1
).
异或来实现
因此,在您的情况下,我们得到以下表达式:
height = (-(legendText->isEmpty()^1) & height);