我正在编写一个需要命令解释器的shell。我目前使用的模式如下:
if(strcmp(command, "my_cmd_keyword1") == 0) {
...
}
else if(strcmp(command, "my_cmd_keyword2") == 0) {
..
}
...
但是,预定义命令关键字的数量可能非常巨大。 if-else分支结果是低效的,因为它必须与每个关键字进行比较(在最坏的情况下)。有没有更有效的方法来处理这个?我正在为我的应用程序使用C / C ++语言。
答案 0 :(得分:3)
您需要函数指针和某种查找表。考虑
std::unordered_map<String, std::function<void(std::string)>>
或一对已排序的
std::vector<>'s
可能会更快。
使用C ++ 11,暂时忽略字符串解析问题,这里有unordered_map和std :: function如何协同工作:
#include <string>
#include <functional>
#include <unordered_map>
std::unordered_map<std::string, std::function<void(const std::string &)>> functions;
void xyz_function(const std::string & commandLine)
{
// this will be called
}
void register_functions()
{
functions["xyz"] = xyz_function;
}
int main()
{
register_functions();
std::string completeCommandLine = "xyz parameter parameter";
std::string exampleCommand = "xyz";
// now look up the command, and run the function registered
functions[exampleCommand](completeCommandLine);
}
答案 1 :(得分:1)
此问题的常见解决方案是将命令名称映射到函数指针的哈希表。 (所有函数必须具有相同的签名;通常,它将包含指向其余命令行参数的指针。)
C ++方便地具有std::unordered_map
(自C ++ 11以来,或者检入boost),这将为您节省大量的实现工作。 Posix(至少从2001年开始)定义<search.h>
header,其中包括一个简单的哈希映射实现。 (与C数据结构库一样,关联的值类型为void*
,因此您需要转换为所需的数据类型。)如果这些都不适合您,那么找到开源哈希表实现并不困难,甚至写一个。