C ++是否有指定值范围的比较运算符? (如“in”在E语言)? [英] Does C++ have comparison operator that specify a range of values? (like 'in' in E language)?

查看:125
本文介绍了C ++是否有指定值范围的比较运算符? (如“in”在E语言)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写一个条件来检查值范围内的枚举变量,就像它可以在E语言中完成:

  enum EnumVariable {a,b,d,g,f,t,k,i} 
if(EnumVariable in [a,g,t,i]){
...
}

如果EnumVariable == a或EnumVariable == b 等等。

在C ++中有更好的方法, >

解决方案

似乎有几个人喜欢我的评论,并要求将其发布为答案,因此: / p>

您可以使用 switch 替换整数 -s在某些值之间。



例如,您的代码可能如下所示:

 枚举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
};

这将非常有效,但只适用于而不是 std :: string ,例如。对于其他类型,您可以尝试使用一些其他答案的建议。



这是一个有点长的写作,但非常,非常高效,并做你需要的。


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

解决方案

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.

这篇关于C ++是否有指定值范围的比较运算符? (如“in”在E语言)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆