4

Often in my code I need to check whether the state of x amount of bools are all true OR all bools are false. So I do:

BOOL first, second, third;
if((first && second && third) || (!first && !second && !third))
     //do something

Being a lazy programmer, I want to know if there is some mathematical shorthand for this kind of query, instead of having to type out this whole thing every time?

4

4 に答える 4

5

The shorthand for all bools the same is testing for (pairwise) equality:

(first==second && second==third)

Of course you can expand this to any number of booleans, having N-1 equality checks joined with the and operator.

于 2012-08-26T16:44:03.887 に答える
3

これが頻繁に必要なものである場合は、整数を使用してビットを個別に読み取る方がよいでしょう。

たとえば、次の代わりに:

BOOL x; // not this
BOOL y; // not this
BOOL z; // not this

...そしてビットフィールドの代わりに(それらのレイアウトは実装定義であるため):

unsigned int x : 1; // not this
unsigned int y : 1; // not this
unsigned int z : 1; // not this

...次のような単一のフィールドを使用します

unsigned int flags; // do this

...そしてすべての値をビットに割り当てます; 例えば:

enum { // do this
  FLAG_X = (1 << 0),
  FLAG_Y = (1 << 1),
  FLAG_Z = (1 << 2),
  ALL_FLAGS = 0x07 // "all bits are on"
};

次に、「すべて偽」をテストするには「 」と言いif (!flags)、「すべて真」をテストするには「」と言いますif (flags == ALL_FLAGS)。ここALL_FLAGSで、はすべての有効なビットを1に設定する数値です。他のビット演算子を使用して、個々のビットを次のように設定またはテストできます。必要です。

この手法には、さらに多くのことを行う前に32個のブール値の上限があることに注意してください(たとえば、より多くのビットを格納するために追加の整数フィールドを作成します)。

于 2012-08-26T18:15:43.267 に答える
2

Check if the sum is 0 or equal to the number of bools:

((first + second + third) % 3 == 0)

This works for any number of arguments.

(But don't take this answer serious and do it for real.)

于 2012-08-26T17:17:44.323 に答える
1

When speaking about predicates, you can usually simplify the logic by using two variables for the quantification operations - universal quantification (for all) and existential quantification (there exists).

BOOL allValues = (value1 && value2 && value3);
BOOL anyValue = (value1 || value2 || value3);

if (allValues || !anyValue) {
   ... do something
}

This would also work if you have a lot of boolean values in an array - you could create a for cycle evaluating the two variables.

于 2012-08-26T18:05:18.413 に答える