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";
^~~~
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 = {
^ ~
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.
Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.
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 initialization syntax to do that.constexpr
//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"},
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With