Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for multiple values when using comparison operators

I've always been under the impression that for any comparison statement, i.e. X == Y or X != Y is the format, and you chain statements together with && or ||.

Is there not some way to write X == (Y || Z) instead of X == Y || X == Z?

Edit: Since it has been established that this is not possible to do cleanly, how else could it be done?

like image 402
Drise Avatar asked Jul 20 '12 16:07

Drise


People also ask

How do you know if a variable contains multiple values?

To check if a variable is equal to one of multiple values:Call the includes() method on the array. The includes method will return true if the value is contained in the array.

What is the === comparison operator used for?

Equal to ( === ) — returns true if the value on the left is equal to the value on the right, otherwise it returns false . Not equal to ( !==

How do you test multiple variables against a single value?

Use the or operator to test multiple variables against a single value, e.g. if a == 'a' or b == 'a' or c == 'a': . The or operator will return True if the value is stored in at least one of the variables.

How do I test multiple parameters in Python?

To test multiple variables x , y , z against a value in Python, use the expression value in {x, y, z} . Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value.


2 Answers

There's no clean way to do what you ask in C++.

What trips many people up is that X == (Y || Z) may be a legal expression and the compiler will not complain. It will just be a bug. Each C++ statement must evaluate to true/false on its own and the operators just string them together. What you're suggesting would require some intrinsic list structure. Many languages have that (like Python), but C++ does not.

like image 110
Adam Avatar answered Sep 20 '22 23:09

Adam


#include <algorithm>
#include <array>
#include <string>
#include <iostream>
#include <initializer_list>
 
template<class Type, class Next>
bool is_one_of(const Type& needle, const Next& next)
{return needle==next;}
template<class Type, class Next, class ... Rest>
bool is_one_of(const Type& needle, const Next& next, Rest... haystack)
{return needle==next || is_one_of(needle, haystack...);}
 
int main() {
    std::string X, Y;
    if (is_one_of(X, Y, "HI"))
        std::cout << "it is!";
    else
        std::cout << "it isn't!";
    return 0;
}

proof of compilation. Xeo also observes that std::any_of, std::all_of and std::none_of may have been useful, depending on your actual needs and desires.

like image 9
Mooing Duck Avatar answered Sep 22 '22 23:09

Mooing Duck