使用#include进行unordered_map初始化

Bry*_*yce 2 c++ data-structures

std::unordered_map<std::string, std::string> mimeMap = {
    #define STR_PAIR(K,V) std::pair<std::string, std::string>(K,V)
    #include "MimeTypes.inc"
};
Run Code Online (Sandbox Code Playgroud)

文件MimeTypes.inc如:

STR_PAIR("3dm", "x-world/x-3dmf"),
STR_PAIR("3dmf", "x-world/x-3dmf"),
STR_PAIR("a", "application/octet-stream"),
STR_PAIR("aab", "application/x-authorware-bin"),
STR_PAIR("aam", "application/x-authorware-map"),
STR_PAIR("aas", "application/x-authorware-seg"),
STR_PAIR("abc", "text/vnd.abc"),
STR_PAIR("acgi", "text/html"),
STR_PAIR("afl", "video/animaflex"),
STR_PAIR("ai", "application/postscript"),
STR_PAIR("aif", "audio/aiff"),
Run Code Online (Sandbox Code Playgroud)

我很迷茫.这段代码如何初始化unordered_map

krz*_*zaq 10

#include文本复制粘贴.这几乎就像你直接写了以下内容:

std::unordered_map<std::string, std::string> mimeMap = {
    #define STR_PAIR(K,V) std::pair<std::string, std::string>(K,V)
    STR_PAIR("3dm", "x-world/x-3dmf"),
    // ...
    STR_PAIR("aif", "audio/aiff"),
}; 
Run Code Online (Sandbox Code Playgroud)

现在,STR_PAIR是一个预处理器宏,用它替换它的参数std::pair<std::string, std::string>(K,V),KV作为宏的参数.例如,上面的代码段与:

std::unordered_map<std::string, std::string> mimeMap = {
    std::pair<std::string, std::string>("3dm", "x-world/x-3dmf"),
    // ...
    std::pair<std::string, std::string>("aif", "audio/aiff"),
}; 
Run Code Online (Sandbox Code Playgroud)

如果您正在使用gcc或clang,则可以使用-E命令行选项获取预处理输出并亲自查看.但请注意,它会非常大.

最后,这样pair用于复制初始化元素mimeMap.

这段代码也越野车,因为mapvalue_typepair<const Key, Value>,所以STR_PAIR实际上应该创建std::pair<std::string const, std::string>