c++中表示等于一组值的简洁方式
Concise way to say equal to set of values in C++
例如,我有以下字符串
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]))
{
// ...
}
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 在c代码之间共享数据的最佳方式
- 在C++中将函数压缩为两种方式
- 以螺旋方式打印矩阵的程序.(工作不好)
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 创建引用向量的优雅方式
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 不同/较旧的处理器运行c++代码的方式是否不同
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 重载方法的方式会在使用临时调用时生成编译器错误
- 在reactor中存储eventHandlers的最佳方式是什么
- 如何以优化的方式同时迭代两个间距不相等的数组
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 如何以简洁的方式安全地访问容器中的每个第 n 个元素?
- 在动态 2-D 数组中填充 0 的更简洁的方式C++
- 简洁灵活的组成字符串的方式
- 声明多维std::数组的更简洁的方式
- c++中表示等于一组值的简洁方式