全局填充地图

时间:2011-06-02 03:13:54

标签: c++ stl initialization global-variables static-initializer

我已全局声明了以下地图并尝试全局填充。

   1: typedef std::map<unsigned short,std::pair<char,std::string>> DeviceTypeList;
   2: DeviceTypeList g_DeviceTypeList;
   3: g_DeviceTypeList.insert( std::make_pair ((unsigned short)SINGLE_CELL_CAMERA,
   std::make_pair('B',"Single Cell Camera")));

显示错误,如错误C2143:语法错误:缺少';'在'。'之前的第2行。

1我做错了什么 2.为什么我们不能全局初始化地图。

2 个答案:

答案 0 :(得分:4)

编译器可能会被第1行的>>弄糊涂(因为它看起来像一个移位运算符)。尝试在那里插入一个空格:

typedef std::map<unsigned short,std::pair<char,std::string> > DeviceTypeList;

[更新]

请参阅Vlad Lazarenko的评论,了解为什么这不会真正解决您的问题。最简单的解决方法是将这个装置包装在一个对象中,在构造函数中初始化它,然后在全局范围内声明一个。 (但是如果你能避免它,那就不是因为全球首先是邪恶的......)

答案 1 :(得分:2)

只有声明和定义可以在全局范围内,并且对map :: insert()的调用不是其中之一。

由于您在模板中使用>>,因此您的编译器必须足够新以支持C ++ 0x。

尝试使用C ++ 0x初始化程序语法:

typedef std::map<unsigned short, std::pair<char,std::string>> DeviceTypeList;
DeviceTypeList g_DeviceTypeList = {
              {(unsigned short)SINGLE_CELL_CAMERA, {'B',"Single Cell Camera"}}
           };

测试:https://ideone.com/t4MAZ

虽然诊断表明它是MSVS,从2010年开始没有C ++ 0x初始化器,所以请尝试使用boost初始化器语法:

typedef std::map<unsigned short, std::pair<char,std::string> > DeviceTypeList;
DeviceTypeList g_DeviceTypeList =
           boost::assign::map_list_of((unsigned short)SINGLE_CELL_CAMERA,
                                       std::make_pair('B',"Single Cell Camera"));

测试:https://ideone.com/KB0vV