How can I succinctly compare a single variable with many different values?

I know that you can write an expression like:

if (num1 != a && num1 != b && num1 != c ..........&& num1 != z) (do something); 

But is there an easier way to compare num1 with 26 other variables? Kinda like:

 if (num1 != a,b,c,d,e,f,g.......) (do something); 
+6
c ++ comparison shortcut
source share
5 answers

If a..g are contiguous constants / values ​​of enum, just use range checking.

 if (num >= a && num <= g) { do_something(); } else { do_something_else(); } 

If they are non-contiguous but constant, then perhaps use the switch statement.

 switch (num) { case a: case b: case c: case d: case e: case f: case g: do_something(); break; default: do_something_else(); break; } 

otherwise, if it's just arbitrary variables or expressions, you just need to do it with a few tests.

+8
source share

You can put a, ... ,z in std::set , and then use the find method of this set to check if num1 is there. This is a logarithmic complexity but does not provide a short circuit.

+5
source share

First of all, a good code construct should not include as many sequences of conditions.

If your case is exactly what it is, this is an attempt to see if there is a number in the list, where the list is actually a set of variables. You can simply enter these numbers in a list (vector) and perform a search operation.

+2
source share

Store the variables in a separate class / hit if the situation allows it.

If your question is more about whether there is syntax in C ++ for a smaler if expression, then perhaps making this clearer in the question.

0
source share

Use std :: find:

 static ValueType values[] = { a, b, ... }; // ... if ( std::find( begin( values ), end( values ), num ) == end( values ) ) 
0
source share

All Articles