将变量与多个值进行比较的最有效方法?

Most efficient way to compare a variable to multiple values?(将变量与多个值进行比较的最有效方法?)
本文介绍了将变量与多个值进行比较的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在我的程序中有几次,我不得不检查变量是否是众多选项之一.例如

A few times in my program, I've had to check if a variable was one of many options. For example

if (num = (<1 or 2 or 3>)) { DO STUFF }

我搞砸了OR",但似乎没有什么是正确的.我试过了

I've messed around with 'OR's, but nothing seems to be right. I've tried

if (num == (1 || 2 || 3))

但它什么都不做.

我想方便地区分几个组.例如

I'd like to conveniently distinguish between several groups. For example

if (num = (1,2,3))

else if (num = (4,5,6))

else if (num = (7,8,9))

推荐答案

如果您要检查的值足够小,您可以创建您要查找的值的位掩码,然后检查要设置的位.

If the values you want to check are sufficiently small, you could create a bit mask of the values that you seek and then check for that bit to be set.

假设您关心几个组.

static const unsigned values_group_1 = (1 << 1) | (1 << 2) | (1 << 3);
static const unsigned values_group_2 = (1 << 4) | (1 << 5) | (1 << 6);
static const unsigned values_group_3 = (1 << 7) | (1 << 8) | (1 << 9);    
if ((1 << value_to_check) & values_group_1) {
  // You found a match for group 1
}
if ((1 << value_to_check) & values_group_2) {
  // You found a match for group 2
}
if ((1 << value_to_check) & values_group_3) {
  // You found a match for group 3
}

这种方法最适合不超过您的 CPU 喜欢使用的自然大小的值.在现代,这通常是 64,但可能会因环境的具体情况而异.

This approach works best for values that don't exceed the natural size your CPU likes to work with. This would typically be 64 in modern times, but may vary depending upon the specifics of your environment.

这篇关于将变量与多个值进行比较的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
Math-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)