このwhile条件を短縮する方法はありますか? 質問する

このwhile条件を短縮する方法はありますか? 質問する
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;
};

ベストアンサー1

もちろん、有効な演算子の文字列を使用して検索することもできます。

#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
}

おすすめ記事