c++ - std::map - C++ 需要所有声明的类型说明符

标签 c++ dictionary

我正在尝试填充 std::map,但出现 2 个编译器错误,我不知道是什么原因。

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

关于c++ - std::map - C++ 需要所有声明的类型说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36323991/

相关文章:

c++ - 尝试做一些简单的事情时抛出 regex_error [ :digit:] or\d

c++ - 在 C++ 字符串中插入空格以分隔字符集

c++ - 从源代码构建 MySQL Connector/C++(找不到 Boost 库错误)

python - 在 Python 中转换为集合字典

python - 使用 map 和 lambda 计算字典中的频率

swift - [String : AnyObject] and [String: Any]? 之间有什么区别

python-3.x - 如何从提供的向量中找到最大的数字?

c++ - 在加载了 dlopen 的库中使用 std::thread 会导致 sigsegv

ios - 从 Application Support Directory 中的 plist 中读取翻译

c++ - 在 vector 中存储字符指针,C++