user5759490
user5759490

Reputation: 113

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

I am trying to fill a std::map, 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 = {
                                   ^         ~

Upvotes: 6

Views: 3424

Answers (1)

Brian Cain
Brian Cain

Reputation: 14619

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"},
};

Upvotes: 10

Related Questions