C++ 将变量与一系列值进行比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3830644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:51:33  来源:igfitidea点击:

Comparing a variable to a range of values

c++

提问by Matthieu M.

In mathematics, the notation 18 < age < 30denotes that age must lie between the values 18 and 30. Is it possible to use this kind of notation in the if statement? For example, I've tried executing

在数学中,符号18 < age < 30表示年龄必须介于值 18 和 30 之间。是否可以在 if 语句中使用这种符号?例如,我试过执行

if(18 < age < 30)

and I get weird output, so it's not quite right. Is there a way to do this or so I simply have to write

我得到了奇怪的输出,所以不太正确。有没有办法做到这一点,或者我只需要写

if(age > 18) /*blah*/;
else if(age < 30) /*same blah*/;

回答by tibur

You can do:

你可以做:

if (18 < age && age < 30) /*blah*/;

回答by Matthieu M.

Nobody answered as to what exactly happened with your code, so let me pick it apart.

没有人回答你的代码到底发生了什么,所以让我把它分开。

Consider the single statement: bool result = 18 < age < 30;

考虑单个语句: bool result = 18 < age < 30;

We want to evaluate the right-hand expression: 18 < age < 30

我们要评估右边的表达式: 18 < age < 30

There are two operators in this expression, and since they are identical, they both have the same priority, in this case, they are thus evaluated from left to right, therefore the expression is equivalent to:

此表达式中有两个运算符,由于它们相同,因此它们具有相同的优先级,在这种情况下,它们因此从左到右计算,因此表达式等效于:

(18 < age) < 30

So let's first examine the left-hand member: 18 < age, it yields a boolean which is either true or false, typically represented as an integral value respectively 1 or 0. Thus the expression can be summed up as:

所以让我们首先检查左边的成员:18 < age,它产生一个布尔值,它要么是真要么是假,通常表示为一个整数值,分别为 1 或 0。因此表达式可以总结为:

{0,1} < 30

which is always true.

这总是正确的。

Therefore, should you use assert(18 < age < 30);it would never backfire.

因此,如果你使用assert(18 < age < 30);它永远不会适得其反。

This implicit conversion between integral (and floating point) built-in types is really annoying...

这种整数(和浮点)内置类型之间的隐式转换真的很烦人......

回答by MSalters

A bit of template code can help here:

一些模板代码可以在这里提供帮助:

template <int min, int max> class range {
  static bool contains(int i) { return min <= i  && i < max; } // In C++, ranges usually are half-open.
};

int age = 23;
if (range<18,30>::contains(age)) { /****/ }

回答by user433534

Is it possible to use this kind of notation in the if statement?

是否可以在 if 语句中使用这种符号?

Yes, possible.

是的,可能。

Desirable, hardly ever: programmers presume the behaviours described in other answers will always apply, so if you dramatically change the order of evaluation and the meaning of an expression then it will really badly confuse them and - sooner or later - cause grief. If you have a very small project with few staff, and they're basically looking to create a domain-specific language in C++, where the domain's notation is really much more readable and familiar using this notation (maybe they're mathematicians not programmers anyway), then you mightin extremis consider something like I present below, though it's still likely to cause trouble.

可取的,几乎从来没有:程序员假定其他答案中描述的行为将始终适用,因此,如果您显着地更改评估顺序和表达式的含义,那么它真的会严重混淆它们,并且迟早会引起悲伤。如果你有一个很小的项目,只有很少的人,而且他们基本上希望用 C++ 创建一种特定于域的语言,使用这种符号,域的符号真的更易读和熟悉(也许他们是数学家而不是程序员) ),那么您可能会在极端情况下考虑我在下面介绍的内容,尽管它仍然可能会引起麻烦。

I've implemented this kind of thing before years ago as an exploratory exercise. If you wish to do so but need help getting started: off the top of my head (i.e. doubtless buggy), consider:

几年前,我已经将这种事情作为探索性练习实施了。如果你想这样做但需要帮助开始:我的头顶(即毫无疑问的越野车),请考虑:

struct Weird
{
    Weird(int n) : n_(n), b_is_meaningful_(false) { }
    Weird(int n, bool b) : n_(n), b_is_meaningful_(true), b_(b) { }

    int n_;

    bool b_is_meaningful_;
    bool b_;
};

Weird operator<(Weird lhs, Weird rhs)
{
    if (lhs.b_is_meaningful_)
        if (!lhs.b_) // effectively, anding with something already known false...
            return Weird(rhs.n_, false);
    return Weird(rhs.n_, lhs.n_ < rhs.n_);
}

Basically, you hack it around until you can:

基本上,你可以破解它,直到你可以:

Weird x = 10;
assert(6 < x < 20 < 30 < Weird(80));

At each point, the operator<creates a new Weirdobject with the Right Hand Side (rhs) value, while updating the boolean state on the assumption that you're effectively anding together a set of comparisons. If you really want to make a mess, you can support all kinds of things in C++, you might have a crack at say "x == 6 || 3 || 56" for fun...?

在每一点上,operator<都会创建一个Weird具有右手边 (rhs) 值的新对象,同时更新布尔状态,假设您有效地将一组比较组合在一起。如果你真的想弄得一团糟,你可以用C++支持各种东西,你可能会为了好玩说“x == 6 || 3 || 56”...?

回答by Arun

You can write a boolean expression as

您可以将布尔表达式写为

((18 < age) && (age < 30))

An expression such as the above can be used whereever a boolean expression is acceptable, for example (but not limited to):

可以在可接受布尔表达式的任何地方使用上述表达式,例如(但不限于):

if((18 < age) && (age < 30)) { ... }

or

或者

bool age_in_range = ((18 < age) && (age < 30));

Note that the above expression uses short-circuit evaluationof operator &&.

注意上面的表达式使用短路评价operator &&

回答by David

Or write yourself a nice set of functions that does this

或者为自己编写一组很好的函数来执行此操作

template <typename type>
bool in_range_[none|both|low|high]<type>( value, min, max )

to cater to all types of boundary included/or not

迎合所有类型的边界包括/或不

(don't use this for floating point)

(不要将此用于浮点数)

In C++0x you could allow and disallow all other possibilities using the "delete" keyword that disables functions for overloads such as < float/double >

在 C++0x 中,您可以使用“delete”关键字来允许和禁止所有其他可能性,该关键字禁用诸如 < float/double > 之类的重载函数

回答by user151019

I know of no way to do exactly as you ask but the normal way is

我知道没有办法完全按照你的要求去做,但正常的方法是

Use the and operator

使用 and 运算符

if (age > 18 && age <30)

如果(年龄> 18 && 年龄<30)