2016-03-07 74 views
0

我需要一個類來從字符串到指向一個函數的const std::map。我怎麼能初始化這個地圖沒有添加元素是這樣的:用C++初始化一個映射

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

+0

的可能的複製[會是什麼一個std ::地圖擴展初始化列表是什麼樣子?](http://stackoverflow.com/questions/3250123/what-would-a-stdmap- extended-initializer-list-look-like) – IInspectable

+0

@IInspectable對不起,我沒有提到我沒有使用C++ 1y。 –

+0

你只需要C++ 11。 – juanchopanza

回答

1

一個典型的方式這樣做我以前做這個預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; 
} 

Live example