Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.?

like image 647
Halona Avatar asked Feb 26 '14 07:02

Halona


People also ask

What operator is used to compare values?

The equality operator (==) is used to compare two values or expressions. It is used to compare numbers, strings, Boolean values, variables, objects, arrays, or functions. The result is TRUE if the expressions are equal and FALSE otherwise.


Video Answer


1 Answers

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.

like image 113
Kiril Kirov Avatar answered Oct 05 '22 11:10

Kiril Kirov