简体   繁体   中英

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 *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

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

( or to the for cycle version).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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