Concise way to say equal to set of values in C++

后端 未结 5 663
后悔当初
后悔当初 2021-01-23 10:35

For example I have the following string,

if (str[i] == \'(\' ||
    str[i] == \')\' ||
    str[i] == \'+\' ||
    str[i] == \'-\' ||
    str[i] == \'/\' ||
    s         


        
5条回答
  •  没有蜡笔的小新
    2021-01-23 11:13

    It really depends on your application actually. For such a small check and depending the context, one acceptable option could be to use a macro

    #include 
    #define IS_DELIMITER(c) ((c == '(') || \
                             (c == ')') || \
                             (c == '+') || \
                             (c == '-') || \
                             (c == '/') || \
                             (c == '*')    )
    
    int main(void)
    {
        std::string s("TEST(a*b)");
    
        for(int i = 0; i < s.size(); i ++)
            std::cout << "s[" << i << "] = " << s[i] << " => " 
                      << (IS_DELIMITER(s[i]) ? "Y" : "N") << std::endl;
        return 0;
    }
    

    A more C++ish way of doing it would be to use an inline function

    inline bool isDelimiter(const char & c)
    {
      return ((c == '(') || (c == ')') || (c == '+') || 
              (c == '-') || (c == '/') || (c == '*')   );
    }
    

    This post might be interesting then : Inline functions vs Preprocessor macros

提交回复
热议问题