我需要一个类来拥有从字符串到函数指针的const std::map
。如何在不添加如下元素的情况下初始化此 map :
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;
编辑:
我在 C++11 之前的版本上执行此操作
最佳答案
我在 C++11 之前使用的一种典型方法是创建一个返回映射的函数,并使用该函数初始化我的 const
变量。
#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;
}
关于c++ - 在 C++ 中预初始化 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35853325/