C++ 在结构中存储函数和运算符

标签 c++ function model structure

如何改进算术解析器中存储函数的数据结构,从中缀符号转换为后缀符号?

此时我使用的是一个char数组的数组:

char *funct[] = { "sin", "cos", "tan"... }
char text[] = "tan";

如果我们将 char 测试为一个函数,这个实现有点困惑并导致以下比较

if ( strcmp ( funct[0], text) == 0 ) || ( strcmp ( funct[1], "text ) == 0 ) || ( strcmp ( func[2], text) == 0 ))
{
  ... do something
}

(或for循环版本)。

如果函数比较多(比较多),索引引用会出错,不清晰。当我们删除/添加新功能时,也有必要更改索引....

如何改进这样的结构,使其易于阅读、易于维护和易于扩展?

我在考虑枚举

typedef enum
{
  Fsin=0,
  Fcos,
  Ftan
} TFunctions;

结果

if ( strcmp ( funct[Fsin], text) == 0 ) || ( strcmp ( funct[Fcos], "text ) == 0 ) || ( strcmp ( func[Ftan], text) == 0 ))
{
...

但可能有更好的解决方案...

最佳答案

您可以使用 std::map。

enum functions
{
    sin,
    cos,
    tan
};

std::map<std::string, unsigned char> func_map;
func_map["sin"] = sin;
func_map["cos"] = cos;
func_map["tan"] = tan;

// then:
std::string text = "cos";

std::map<char*, unsigned char>::iterator it;
it = func_map.find(text);

if(it != func_map.end())
{
    // ELEMENT FOUND
    unsigned char func_id = it->second;
}
else
{
    // NOT FOUND
}

关于C++ 在结构中存储函数和运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13220829/

相关文章:

javascript - 如何从多个异步函数调用返回响应?

python - 对一个函数使用不同的文件,但由于使用 with 而导致 I/O 错误

ruby-on-rails - Rails 中的子类化模型

c++ - 枚举作为 C++ 中函数的返回类型

php - 为 PHP 编写 C/C++ 绑定(bind)和库

c++ - DirectX 11 输入读取方法

javascript - 从函数返回 boolean 值

python - 为什么在没有任何导出功能的情况下 boost python 构建的库?

laravel - 将 Eloquent 模型限制为特定列

sql - Django:ManyToManyField,带有附加列