std::map-C++要求所有声明都有一个类型说明符

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

本文关键字:有一个 说明符 声明 类型 map-C++ std      更新时间:2023-10-16

我正在尝试填充std::map,但我遇到了两个编译器错误,我不知道原因是什么。

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

这些就是错误:

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

这会导致完全不同类型的错误:

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 = {
                                   ^         ~

您之所以出现此错误,是因为您试图在文件范围内执行语句。在函数中定义这些赋值,就不会再出现这些错误了。

如果要在静态初始化期间填充此map,可以使用boost::assignconstexpr初始化语法来执行此操作。

//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"},
};
相关文章: