To store the lookup index, you would use std::map
. This comprises key-value pairs (mymap[ key ] = value
). C++ allows you to store a pointer to a function, here I use the using
keyword to create a type name, func_t, of the type of fingerprint our function will have: void (*)(void)
(this is how you say "pointer to a function which takes void and returns void).
#include <iostream>
#include <string>
#include <map>
// the functions we intend to map
void disp1()
{
std::cout<<"Disp1\n";
}
void disp2()
{
std::cout<<"Disp2\n";
}
void disp3()
{
std::cout<<"Disp3\n";
}
int main() {
// create a new type, func_t, which describes a pointer
// to a void function that takes no parameters (void).
using func_t = void (*)(void);
// declare a map from a string key to a func_t value,
// and initialize it with a mapping of f1->disp1, f2->disp2
// and f3->disp3
std::map<std::string, func_t> functionMap = {
{ "f1", disp1 }, { "f2", disp2 }, { "f3", disp3 }
};
// declare a string for reading input
std::string input;
// loop until there is no more input on std::cin.
while (std::cin.good()) {
// prompt
std::cout << "Which disp (f1, f2, f3)? ";
// fetch the next line of text from cin, without the \n
std::getline(std::cin, input);
// if the input is empty we ran out of input or the user
// input a blank line. either way, stop.
if (input.empty())
break;
std::cout << "You chose " << input << "\n";
// look for the key in the map. if the key is not found,
// it will equal the special iterator functionMap.end()
auto it = functionMap.find(input);
// If it's not functionMap.end then we have a valid iterator.
// it->first is the key, it->second is the function pointer.
if (it != functionMap.end()) {
// to use a function pointer, just add the () with any
// arguments after the variable name.
// remember, it->second is the function pointer.
it->second();
} else {
std::cout << "Invalid entry.\n";
}
}
}
Live demo: http://ideone.com/4Xlow1