0

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?

2
  • std::map is what you're looking for. Commented Mar 9, 2014 at 0:04
  • 3
    Or std::unordered_map, if complexity should be O(1) and hashing O(m). Commented Mar 9, 2014 at 0:06

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.