c++中表示等于一组值的简洁方式

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

本文关键字:简洁 方式 于一组 表示 c++      更新时间:2023-10-16

例如,我有以下字符串

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

我的问题是有一个简洁的方式来说,如果这个值在c++中的这些值的集合之一?

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

并不光荣,因为它是C而不是c++,但是C标准库总是可以从c++代码访问,作为一个老恐龙,我的第一个想法是:

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

简洁紧凑

您可以使用以下命令:

const char s[] = "()+-/*";
if (std::any_of(std::begin(s), std::end(s), [&](char c){ return c == str[i]})) {
     // ...
}

这实际上取决于您的应用程序。对于如此小的检查,根据上下文,一个可接受的选项是使用宏

#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;
}
的c++ 方法是使用内联函数
inline bool isDelimiter(const char & c)
{
  return ((c == '(') || (c == ')') || (c == '+') || 
          (c == '-') || (c == '/') || (c == '*')   );
}

这篇文章可能会很有趣:内联函数vs预处理器宏

也许不是"更简洁",但我认为这种风格在测试点上是简洁的和富有表现力的

当然,is_arithmetic_punctuation不必是一个lambda,如果你要使用它不止一次。它可以是一个函数或一个函数对象。

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