Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

dictionary

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 = {
                                   ^         ~
like image 343
user5759490 Avatar asked Mar 31 '16 04:03

user5759490


People also ask

What does C++ requires a type specifier for all declarations?

This error occurs when you do not specify the datatype of a variable or you forget to specify the return type of a method or a function. Specifying the datatype of variables or the return-type of methods is necessary for C++ because it is a statically-typed language.

Is std :: map ordered?

Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.


1 Answers

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"},
};
like image 163
Brian Cain Avatar answered Sep 20 '22 12:09

Brian Cain