简体   繁体   中英

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

For example I have the following string,

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

My question is there a concise way to say if this value one of these set of values in c++?

您可以使用特殊字符在字符串中搜索单个字符str[i]std::string("()+-/*").find(str[i]) != std::string::npos

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

You may use the following:

const char s[] = "()+-/*";

if (std::any_of(std::begin(s), std::end(s), [&](char c){ return c == str[i]})) {
     // ...
}

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

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]))
{
  // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM