用旗阵用旗阵

2023-09-11 05:49:47 作者:你会腻我何必

让说我有布尔标志数组,将它设置为true或false取决于条件。

让说,指数1,2,6已定,其他所有标志都没有设置,我需要调用泛函,如果指数2,3,5已设置和所有其他标志都没有设置,我需要调用 functionB 。有没有一种简单的方法,我可以执行上述逻辑以外做这样的:

 如果(阵列[1] ==真&功放;&放大器;数组[2] ==真&功放;&放大器;数组[6] ==真&功放;&安培;
   阵列[3] ==假放;&安培;数组[4] ==假放;&安培;阵列[5] == FALSE)
{
  泛函();
}
 
亚运火炬传递北京启动仪式 现场旗阵歌舞表演

解决方案

维护和可读性的噩梦!

考虑这个:

 布尔temperature_sensor_tripped(常量bool_array和放大器;标志)
{
     的返回标志[1];
}

// [...]

如果(temperature_sensor_tripped(阵列)
    &功放;&安培; moisture_sensor_tripped(阵列)
    &功放;&安培; !alarm_dispatched(阵列))
{
    泛函();
}
 

这有一个 moisture_sensor_tripped的优势()及其亲属可以从其他的功能被称为没有你(或维护)记住的标记的顺序。

Let say I have an array of bool flags, it would be set to true or false depends on the condition.

Let say the index 1 ,2 ,6 have been set and all other flags are not set, I need to call functionA, and if index 2,3, 5 have been set and all other flags are not set, I need to call functionB. Is there an easy way where I could perform the logic above other than doing this:

if(array[1] == true && array[2] == true && array[6] == true && 
   array[3] == false && array[4] == false && array[5] == false)
{
  functionA();
}

解决方案

Maintenance and readability nightmare!

Consider this instead:

bool temperature_sensor_tripped(const bool_array& flags)
{
     return flags[1];
}

// [...]

if (temperature_sensor_tripped(array) 
    && moisture_sensor_tripped(array)
    && !alarm_dispatched(array))
{
    functionA();
}

This has the advantage that moisture_sensor_tripped() and its kin can be called from other functions without you (or the maintainer) remembering the order of the flags.

相关推荐