[英]Is it proper to use multiple 'greater-than / less-than' comparators in an evaluation?
I was trying to see if a variable was within a range by using multiple greater-than (>)
's and less-than (<)
's in one evaluation. 我试图通过在一个评估中使用多个
greater-than (>)
和less-than (<)
来查看变量是否在范围内。 I was unsure whether this works or not though. 我不确定这是否行得通。 It seems than using multiple =='s is illigal , but is it okay with < and >'s?
似乎使用多个==是非法的 ,但使用<和>可以吗?
Here's an example of what I'm trying to do: 这是我要执行的操作的一个示例:
if (bottomOfRange < variable < topOfRange) {
//Do stuff
}
I know that this: 我知道这:
if (bottomOfRange < varialbe && variable < topOfRange) {
//Do stuff
}
works, I'm just looking for an even more efficient way of comparing. 的作品,我只是在寻找一种更有效的比较方式。
Will this evaluate how I want, or will it act differently? 这会评估我的意愿,还是会有所不同?
No. This code will probably compile, depending on the types of the variables, but won't give the comparison you want. 不会。此代码可能会根据变量的类型进行编译,但不会提供所需的比较。 It will:
它会:
bottomOfRange < variable
to give a boolean result; bottomOfRange < variable
以给出布尔结果; topOfRange
. topOfRange
进行比较。 If you want to compare a value against two other values, then you need to write out the two comparisons: 如果要将一个值与其他两个值进行比较,则需要写出两个比较:
if (bottomOfRange < variable && variable < topOfRange)
Assuming that bottomOfRange
and topOfRange
are built-in types, then no, it won't accomplish anything useful. 假设
bottomOfRange
和topOfRange
是内置类型,则不会,它不会完成任何有用的工作。
If you want to badly enough, you could define a type that overloaded operator<
to make it actually work though: 如果您想做的足够糟糕,可以定义一个重载
operator<
的类型,以使其实际上可以工作:
class range {
int lower;
int val;
range(int lower, int val) : lower(lower), val(val) {}
public:
bool operator < (int upper) {
return lower < val && val < upper;
}
class start {
int t;
public:
start(int t) : t(t) {}
range operator < (int val) { return range(t, val); }
};
};
#ifdef TEST
#include <iostream>
int main(){
static char const *s [] = { "Out of range", "In range" };
int variable = 20;
range::start bottomOfRange(10);
int topOfRange(30);
if (bottomOfRange < variable < topOfRange)
std::cout << "In range\n";
else
std::cout << "out of range\n";
bottomOfRange = 30;
topOfRange = 10;
if (bottomOfRange < variable < topOfRange)
std::cout << "In range\n";
else
std::cout << "Out of range\n";
}
#endif
Result: 结果:
In range
Out of range
Warning: this is intended primarily (purely?) as a curio. 警告:这主要(纯粹是?)用作古玩。 Although it obviously supports exactly what you've asked for, I'd be pretty hesitant about using it in my own code, and I'm not really recommending that you use it in yours either.
尽管它显然可以完全支持您的要求,但对于在我自己的代码中使用它,我还是很犹豫的,我也不建议您在自己的代码中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.