user5759490 user5759490 - 3 years ago 315
C++ Question

std::map - C++ requires a type specifier for all declarations

I am trying to fill a

, but I am getting 2 compiler errors, and I don't know what the cause is.

std::map<std::string, std::string> dirFull;
dirFull["no"] = "north";
dirFull["so"] = "south";
dirFull["ea"] = "east";
dirFull["we"] = "west";
dirFull["nw"] = "north-west";
dirFull["ne"] = "north-east";
dirFull["sw"] = "south-west";
dirFull["se"] = "south-east";

Those are the errors:

error: C++ requires a type specifier for all declarations
dirFull["no"] = "north";
error: size of array has non-integer type 'const char[3]'
dirFull["no"] = "north";

I have also tried this:

std::map<std::string, std::string> dirFull = {
{"no", "north"}, {"so", "south"},
{"ea", "east"}, {"we", "west"},
{"ne", "north-east"}, {"nw", "north-west"},
{"se", "south-east"}, {"sw","south-west"} };

This results in a complete different type of error:

error: non-aggregate type 'std::map<std::string, std::string>' (aka '...') cannot be initialized with an initializer list
std::map<std::string, std::string> dirFull = {
^ ~

Answer Source

You're getting this error because you're trying to execute statements at file scope. Define these assignments in a function and you will not get these errors anymore.

If you want to populate this map during static initialization time, you can use boost::assign or constexpr initialization syntax to do that.

//requires c++11:
const map <string,string> dirFull = {
    {"no",   "north"},
    {"so",   "south"},
    {"ea",   "east"},
    {"we",   "west"},
    {"nw",   "north-west"},
    {"ne",   "north-east"},
    {"sw",   "south-west"},
    {"se",   "south-east"},
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download