简体   繁体   English

哈希表,其中键是字符串,值是c ++中的函数

[英]Hash table where key is string and value is function in c++

Is it possible to have an implementation for hash, where key is String and value is function . 是否有可能有一个hash实现,其中key是String ,value是function For the background, I have a program where there is lots of string comparison, ie 对于后台,我有一个程序,其中有很多字符串比较,即

if(strcasecmp(s,"london")==0) 
   functionA();  
else if(strcasecmp(s,"moscow")==0)
   functionB();  
else if(strcasecmp(s,"delhi")==0)  
   functionC();  
  ...  

and so on. 等等。

But this kind of implementation is very costly (theta(n)) , since String comparison is done for all the if statements. 但是这种实现非常昂贵(theta(n)) ,因为对所有if语句进行了String比较。 If we have an hash implementation where key is String and value is function , we can just call something like 如果我们有一个哈希实现,其中key是String ,value是function ,我们可以调用类似的东西

function = hash.Get("moscow");    
function(); 

Its complexity is good (theta(log(1))) . 它的复杂性很好(theta(log(1)))

Is it possible to do this? 是否有可能做到这一点?

Is it possible to have an implementation for hash, where key is String and value is function? 是否有可能有哈希的实现,其中键是字符串,值是函数?

Yes. 是。 This is perfectly feasible. 这是完全可行的。 You can use pointers to function or std::function . 您可以使用指针函数或std::function Possible containers might be: 可能的容器可能是:

  1. std::unordered_map 的std :: unordered_map
  2. boost::unordered_map 提高:: unordered_map

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

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