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

后端 未结 5 624
后悔当初
后悔当初 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:02

    You can search for single character str[i] in a string with your special characters: std::string("()+-/*").find(str[i]) != std::string::npos

    0 讨论(0)
  • 2021-01-23 11:08

    Not glorious because it is C instead of C++, but the C standard library is always accessible from C++ code, and my first idea as an old dinosaur would be:

    if (strchr("()+-/*", str[i]) != NULL)
    

    Simple and compact

    0 讨论(0)
  • 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 <iostream>
    #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

    0 讨论(0)
  • 2021-01-23 11:15

    Maybe not "more concise", but I think this style is succinct and expressive at the point of the test.

    Of course is_arithmetic_punctuation needn't be a lambda if you're going to use it more than once. It could be a function or a function object.

    auto is_arithmetic_punctuation = [](char c)
    {
      switch(c)
      {
          case '(':
          case ')':
          case '+':
          case '-':
          case '/':
          case '*':
              return true;
          default:
              return false;
      }
    };
    
    if (is_arithmetic_punctuation(str[i]))
    {
      // ...
    }
    
    0 讨论(0)
  • 2021-01-23 11:19

    You may use the following:

    const char s[] = "()+-/*";
    
    if (std::any_of(std::begin(s), std::end(s), [&](char c){ return c == str[i]})) {
         // ...
    }
    
    0 讨论(0)
提交回复
热议问题