Search code examples
c++comparison-operators

Does C++ have comparison operator that specify a range of values? (like 'in' in E language)?


I need to write a condition that checks if an enum variable in range of values, like it can be done in E language:

enum EnumVariable {a, b, d, g, f, t, k, i};
if (EnumVariable in [ a, g, t, i]) {
    ...
}

Is there a better way in C++ than ask 4 times if EnumVariable==a or EnumVariable==b etc.?


Solution

  • It appeared, that several people liked my comment and asked to post it as an answer, so:

    You can actually use switch for integral types without break-s between some values.

    For example, your code could look like:

    enum EnumVariable {a, b, d, g, f, t, k, i};
    switch( EnumVariable )
    {
    case a:
    case g:
    case t:
    case i:
        // do something
        break;
    // handler other values
    };
    

    This would be very efficient, but would work for integral types only, and not for std::string, for example. For other types, you may try to use some of the other answers' suggestions.

    It's a bit long for writing, but very, very efficient and does what you need.