gpt4 book ai didi

c++ - 开关盒中的多个条件?

转载 作者:IT老高 更新时间:2023-10-28 23:03:24 26 4
gpt4 key购买 nike

我可以使用 switch case 来检查多个条件吗?例如,如果满足其中一个条件,它会执行它的情况吗?

switch (conditionA or conditionB fullfilled)
{ //execute code }

最佳答案

显然,如果条件A 或条件B 为true,如何执行代码的问题可以用if(conditionA || conditionB) 轻松回答,没有 switch 语句是必要的。如果出于某种原因必须使用 switch 语句,则可以通过建议 case 标签作为其他答案之一再次简单地回答该问题可以。

我不知道这些琐碎的答案是否完全涵盖了OP的需求,但是除了OP之外,很多人都会阅读这个问题,所以我想提出一个更通用的解决方案,可以解决许多类似的问题对于那些琐碎的答案根本行不通。

如何使用单个 switch 语句同时检查任意数量的 bool 条件的值。

它很hacky,但它可能会派上用场。

诀窍是将每个条件的 true/false 值转换为位,将这些位连接成 int 值,然后在 int 值上进行 switch

下面是一些示例代码:

#define A_BIT (1 << 0)
#define B_BIT (1 << 1)
#define C_BIT (1 << 2)

switch( (conditionA? A_BIT : 0) | (conditionB? B_BIT : 0) | (conditionC? C_BIT : 0) )
{
case 0: //none of the conditions holds true.
case A_BIT: //condition A is true, everything else is false.
case B_BIT: //condition B is true, everything else is false.
case A_BIT + B_BIT: //conditions A and B are true, C is false.
case C_BIT: //condition C is true, everything else is false.
case A_BIT + C_BIT: //conditions A and C are true, B is false.
case B_BIT + C_BIT: //conditions B and C are true, A is false.
case A_BIT + B_BIT + C_BIT: //all conditions are true.
default: assert( FALSE ); //something went wrong with the bits.
}

然后,如果您有非此即彼的情况,您可以使用 case 标签失败。例如:

switch( (conditionA? A_BIT : 0) | (conditionB? B_BIT : 0) | (conditionC? C_BIT : 0) )
{
case 0:
//none of the conditions is true.
break;
case A_BIT:
case B_BIT:
case A_BIT + B_BIT:
//(either conditionA or conditionB is true,) and conditionC is false.
break;
case C_BIT:
//condition C is true, everything else is false.
break;
case A_BIT + C_BIT:
case B_BIT + C_BIT:
case A_BIT + B_BIT + C_BIT:
//(either conditionA or conditionB is true,) and conditionC is true.
break;
default: assert( FALSE ); //something went wrong with the bits.
}

.

关于c++ - 开关盒中的多个条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8644096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com