簡體   English   中英

C ++在結構中存儲函數和運算符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM