如何改进用于将算术解析器中的函数从中缀转换为后缀表示法的数据结构?
目前,我正在使用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
}