是否可以实现哈希,其中键是 String
,值是 function
。对于背景,我有一个程序,其中有很多字符串比较,即
if(strcasecmp(s,"london")==0)
functionA();
else if(strcasecmp(s,"moscow")==0)
functionB();
else if(strcasecmp(s,"delhi")==0)
functionC();
...
等等。
但是这种实现的成本非常高(theta(n))
,因为String
比较是针对所有if 语句进行的。如果我们有一个散列实现,其中键是 String
,值是 function
,我们可以调用类似
function = hash.Get("moscow");
function();
它的复杂度很好(theta(log(1)))
。
这有可能吗?
最佳答案
Is it possible to have an implementation for hash, where key is String and value is function?
是的。这是完全可行的。您可以使用指向函数或 std::function
的指针。可能的容器可能是:
- std::unordered_map
- boost::unordered_map
关于c++ - 哈希表,其中键是字符串,值是 C++ 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22276713/