如何改进算术解析器中存储函数的数据结构,从中缀符号转换为后缀符号?
此时我使用的是一个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/