c++ - 有没有办法缩短这个while条件?

标签 c++ algorithm if-statement while-loop simplify

while (temp->left->oper == '+' || 
       temp->left->oper == '-' || 
       temp->left->oper == '*' || 
       temp->left->oper == '/' || 
       temp->right->oper == '+' || 
       temp->right->oper == '-' || 
       temp->right->oper == '*' || 
       temp->right->oper == '/')
{
    // do something
}

为了清楚起见:temp 是指向以下 node 结构的指针:

struct node
{
    int num;
    char oper;
    node* left;
    node* right;
};

最佳答案

当然,您可以只使用一串有效的运算符并搜索它。

#include <cstring>

// : :

const char* ops = "+-*/";
while(strchr(ops, temp->left->oper) || strchr(ops, temp->right->oper))
{
     // do something
}

如果您关心性能,那么也许可以查找表:

#include <climits>

// : :

// Start with a table initialized to all zeroes.
char is_op[1 << CHAR_BIT] = {0};

// Build the table any way you please.  This way using a string is handy.
const char* ops = "+-*/";
for (const char* op = ops; *op; op++) is_op[*op] = 1;

// Then tests require no searching
while(is_op[temp->left->oper] || is_op[temp->right->oper])
{
     // do something
}

关于c++ - 有没有办法缩短这个while条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57157372/

相关文章:

c++ - 相同的代码,相同的库版本,相同的编译器,不同的输出

algorithm - 有序集合中的高效插入

c++ - Xerces XML 解析器,将 XMLCh* 转换为浮点型

c++ - cppcheck - 终止Strncpy

java - 两个数相加得到一个值的算法

java - 交替字符的 String 方法的输出

java - 二元运算符 '&&' 的错误操作数。请帮我找出问题所在

c - 我如何在 && if 语句中使用 2 个数组

if-statement - Lua 中的链式逻辑操作

c++ - 表示类中日期的最佳方式(日月年与时间戳)