I know you can write a statement like:
if (num1 != a && num1 != b && num1 != c ..........&& num1 != z)
(do something);
But is there an easier way to compare the num1 variable to 26 other variables? Kinda like:
if (num1 != a,b,c,d,e,f,g.......)
(do something);
If a..g
are contiguous constant/enum values then just use a range check.
if (num >= a && num <= g)
{
do_something();
}
else
{
do_something_else();
}
If they are non-contiguous but constant then maybe use a 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 they are just arbitrary variables or expressions then you may have just have to do it with multiple tests.
You can put a, ... ,z
into a std::set
and then use the find
method of that set to check if num1
is in there. This has logarithmic complexity, but does not allow for short-circuiting.
First of all, a good code design should not include so many sequence of conditions.
If your case is exactly the way it is, that is trying to see if a number exists in a list, where the list is actually a collection of variables. You could simply enter those numbers into the list( vector ) and perform find operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With