【发布时间】:2011-02-07 20:12:33
【问题描述】:
我只需要字典或关联数组string => int。
这种情况下有类型映射 C++。
但我只需要一个映射用于所有实例(-> 静态),并且此映射不能更改(-> const);
我在 boost 库中找到了这种方式
std::map<int, char> example =
boost::assign::map_list_of(1, 'a') (2, 'b') (3, 'c');
没有这个库还有其他解决方案吗? 我尝试过类似的方法,但地图初始化总是存在一些问题。
class myClass{
private:
static map<int,int> create_map()
{
map<int,int> m;
m[1] = 2;
m[3] = 4;
m[5] = 6;
return m;
}
static map<int,int> myMap = create_map();
};
【问题讨论】:
-
你指的是什么问题?您是否尝试从另一个全局静态变量/常量中使用此映射?
-
这不是关联数组字符串 => int,您将 int 映射到 char。
v = k + 'a' - 1.
标签: c++ static map initialization constants