Home > Net >  Cpp initialize std::map in header
Cpp initialize std::map in header

Time:10-12

I want to initialize a std::map in my_cpp.h header file:

std::map<std::string, double> my_map;
my_map["name1"] = 0;
my_map["name2"] = 0;

But there was a compile error showed up:

error: ‘my_map’ does not name a type

Can someone explain why this not work for a C newbie? Thanks

CodePudding user response:

You can't initialize a map in a .h file like that. Those assignment statements need to be inside a function/method instead.

Otherwise, initialize the map directly in its declaration, eg

std::map<std::string, double> my_map = {
    {"name1", 0.0},
    {"name2", 0.0}
};

CodePudding user response:

The header file is just a declaration, or initialize the map directly . You can modify your code like this:

#include <map>
#include <string>

const std::map<std::string, double> my_map = {
  { "name1", 0 },
  { "name2", 0 }
};
  • Related