[英]C++ storing functions and operators in a 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
}
为了获得最快的代码,您可能需要如下所示的映射:
typedef std::map<std::string, func_t> func_map;
func_map fm;
fm["sin"] = sin_func(); // get value of this entry from somewhere
fm["cos"] = cos_func(); // for example sin_func or cos_func
auto i = fm.find( "sin" );
if( i != fm.end() ) {
func_t f = i->second; // value found, we may use it.
}
另外,如果确实有很多项目,则可以使用std::unordered_map
代替std::map
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.