fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4.  
  5. // the functions we intend to map
  6. void disp1()
  7. {
  8. std::cout<<"Disp1\n";
  9. }
  10.  
  11. void disp2()
  12. {
  13. std::cout<<"Disp2\n";
  14. }
  15.  
  16. void disp3()
  17. {
  18. std::cout<<"Disp3\n";
  19. }
  20.  
  21. int main() {
  22. // create a new type, func_t, which describes a pointer
  23. // to a void function that takes no parameters (void).
  24. using func_t = void (*)(void);
  25. // declare a map from a string key to a func_t value,
  26. // and initialize it with a mapping of f1->disp1, f2->disp2
  27. // and f3->disp3
  28. std::map<std::string, func_t> functionMap = {
  29. { "f1", disp1 }, { "f2", disp2 }, { "f3", disp3 }
  30. };
  31.  
  32. // declare a string for reading input
  33. std::string input;
  34.  
  35. // loop until there is no more input on std::cin.
  36. while (std::cin.good()) {
  37. // prompt
  38. std::cout << "Which disp (f1, f2, f3)? ";
  39. // fetch the next line of text from cin, without the \n
  40. std::getline(std::cin, input);
  41. // if the input is empty we ran out of input or the user
  42. // input a blank line. either way, stop.
  43. if (input.empty())
  44. break;
  45.  
  46. std::cout << "You chose " << input << "\n";
  47.  
  48. // look for the key in the map. if the key is not found,
  49. // it will equal the special iterator functionMap.end()
  50. auto it = functionMap.find(input);
  51. // If it's not functionMap.end then we have a valid iterator.
  52. // it->first is the key, it->second is the function pointer.
  53. if (it != functionMap.end()) {
  54. // to use a function pointer, just add the () with any
  55. // arguments after the variable name.
  56. // remember, it->second is the function pointer.
  57. it->second();
  58. } else {
  59. std::cout << "Invalid entry.\n";
  60. }
  61. }
  62. }
Success #stdin #stdout 0s 3468KB
stdin
f1
f3
f2
stdout
Which disp (f1, f2, f3)? You chose f1
Disp1
Which disp (f1, f2, f3)? You chose f3
Disp3
Which disp (f1, f2, f3)? You chose f2
Disp2
Which disp (f1, f2, f3)?