Hi friends,
Can you please help me with the syntax of how I will map a string to a function pointer using map stl?
Thanks
#include <iostream>
#include <map>
#include <string>
std::string foo() { return "Foo"; }
std::string bar() { return "Bar"; }
int main()
{
std::map<std::string, std::string (*)()> m;
// Map the functions to the names
m["foo"] = &foo;
m["bar"] = &bar;
// Display all of the mapped functions
std::map<std::string, std::string (*)()>::const_iterator it = m.begin();
std::map<std::string, std::string (*)()>::const_iterator end = m.end();
while ( it != end ) {
std::cout<< it->first <<"\t\""
<< (it->second)() <<"\"\n";
++it;
}
}
Fire point-blank:
#include <iostream>
#include <string>
#include <map>
using namespace std;
namespace // for example only
{
void DoOne() { cout << "One" << endl; }
void DoTwo() { cout << "Two" << endl; }
void DoNil() { cout << "Nil" << endl; }
}
void Mapper()
{
typedef void (*DoIt)();
typedef map<string,DoIt> MapCall;
MapCall doit;
doit.insert(MapCall::value_type("One",DoOne));
doit.insert(MapCall::value_type("Two",DoTwo));
doit.insert(MapCall::value_type("Nil",DoOne));
MapCall::const_iterator call;
call = doit.find("One");
if (call != doit.end())
(*call).second();
else
cout << "Unknown call requested" << endl;
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.