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?
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.
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 ( !==
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.
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.
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.
#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.
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