简体   繁体   English

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

[英]C++ storing functions and operators in a structure

How to improve a data structure for storing functions in arithmetic parser converting from infix to postfix notation? 如何改进用于将算术解析器中的函数从中缀转换为后缀表示法的数据结构?

At this moment I am using an array of char arrays: 目前,我正在使用char数组的数组:

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

This impementation is a little bit confused and leads to the following comparisions, if we test char to be a function 如果我们将char测试为一个函数,则这种实现有点混乱,并导致以下比较

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

( or to the for cycle version). (或为for循环版本)。

If there are a lot of functions (and a lot of comparisions), the index referencing leads to errors and it is not clear. 如果有很多功能(和很多比较),则索引引用会导致错误,并且不清楚。 There is also a necessity to change the index when we remove/add a new function.... 当我们删除/添加新功能时,也有必要更改索引。

How to improve such a structure so as it is easy to read, easy to maintain and easy to scale up? 如何改善这种结构以使其易于阅读,易于维护和易于扩展?

I was thinking about enum 我在想枚举

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

which results to 导致

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

but there may be a better solution... 但可能有更好的解决方案...

You can use std::map. 您可以使用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
}

For fastest code you may have some kind of map as follow: 为了获得最快的代码,您可能需要如下所示的映射:

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.
}

Also if there is really a lot of items you may use std::unordered_map instead of std::map 另外,如果确实有很多项目,则可以使用std::unordered_map代替std::map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM