fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <functional>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8. void f_1234() { cout << "1234\n"; }
  9.  
  10. void f_ABCD() { cout << "ABCD\n"; }
  11.  
  12. void f_default() { cout << "default\n"; }
  13.  
  14. void f( const char* s )
  15. {
  16. using function_t = std::function< void() >;
  17. using string_to_function = map< string, function_t >;
  18.  
  19. static string_to_function m =
  20. {
  21. {"1234", f_1234}, // assosciate "1234" to function f_1234
  22. {"ABCD", f_ABCD}, // assosciate "ABCD" to function f_ABCD
  23. };
  24.  
  25. auto i = m.find( s );
  26.  
  27. return i == m.end()
  28. ? f_default() // not found in map
  29. : i->second(); // found, so we call the function
  30. }
  31.  
  32. int main()
  33. {
  34. f( "1234" );
  35. f( "ABCD" );
  36. }
  37.  
Success #stdin #stdout 0s 4340KB
stdin
Standard input is empty
stdout
1234
ABCD