0

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

3
Contributors
2
Replies
5
Views
8 Years
Discussion Span
Last Post by ArkM
0
#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;
  }
}
0

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;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.