Ayush Gupta
Ayush Gupta

Reputation: 1717

Preinititalize a map in C++

I need a class to have a const std::map from string to pointer to a function. How can I initialize this map without adding elements like this:

string func1(string a){
    return a;
}

string func2(string x){
    return "This is a random string";
}

//In class declaration:
   const map<string,string(*)(string)> a;

//Where should this go? Any other, probably better method to initialize this map?
    a["GET"] = &func1;
    a["SET"] = &func2;

EDIT:

I am doing this on pre-C++11

Upvotes: 0

Views: 150

Answers (1)

user2093113
user2093113

Reputation: 3560

A typical way I used to do this pre-C++11 was to create a function that returns the map and initialise my const variable using that function.

#include <algorithm>
#include <iostream>
#include <map>
#include <string>

typedef std::map<std::string, std::string(*)(std::string)> MyMap;

std::string forward(std::string s) { return s; }
std::string backward(std::string s) { std::reverse(s.begin(), s.end()); return s; }

MyMap Init()
{
    MyMap map;
    map["forward"] = &forward;
    map["backward"] = &backward;
    return map;
}

const MyMap Map = Init(); // <--- initialise map via function

int main()
{
    for (MyMap::const_iterator iter = Map.begin(); iter != Map.end(); iter++)
        std::cout << (*iter->second)(iter->first) << "\n";
    return 0;
}

Live example

Upvotes: 1

Related Questions