Vikram Ranabhatt
Vikram Ranabhatt

Reputation: 7630

populating map globally

I have declared the following map globally and trying to populate globally.

   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")));

it is showing error like error C2143: syntax error : missing ';' before '.' at line2.

1 Am I doing something wrong
2. why can't we initialize the map globally.

Upvotes: 1

Views: 3293

Answers (2)

Cubbi
Cubbi

Reputation: 47498

Only declarations and definitions can be in global scope, and the call to map::insert() is not one of them.

Since you're using >> in templates, your compiler must be new enough for C++0x support.

Try the C++0x initializer syntax then:

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

test: https://ideone.com/t4MAZ

Although the diagnostic suggests it is MSVS, which doesn't have C++0x initializers as of 2010, so try the boost initializer syntax instead:

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"));

test: https://ideone.com/KB0vV

Upvotes: 2

Nemo
Nemo

Reputation: 71615

Compiler is probably getting confused by the >> on line 1 (because it looks like a shift operator). Try inserting a space in there:

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

[update]

See Vlad Lazarenko's comment for why this will not actually solve your problem. Easiest fix is to wrap this contraption in an object, initialize it in the constructor, then declare one at global scope. (But not if you can avoid it since globals are evil in the first place...)

Upvotes: 4

Related Questions