quartz
quartz

Reputation: 757

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. For the background, I have a program where there is lots of string comparison, i.e.

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. If we have an hash implementation where key is String and value is function, we can just call something like

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

Its complexity is good (theta(log(1))).

Is it possible to do this?

Upvotes: 0

Views: 146

Answers (1)

4pie0
4pie0

Reputation: 29724

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. Possible containers might be:

  1. std::unordered_map
  2. boost::unordered_map

Upvotes: 2

Related Questions