简体   繁体   中英

How can I concisely compare a single variable to many different values?

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.

Store the variables in a seperate class / struck if the situation allows for that.

If your question is more about if there is a syntax in c++ to allow a smaler if statement, then perhaps make that clearer in the question.

Use std::find:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM