代码之家  ›  专栏  ›  技术社区  ›  user2138149

为什么std::unordered_映射不能与const std::string键一起工作?

  •  1
  • user2138149  · 技术社区  · 8 年前

    下面的代码示例不会编译,但是可以通过删除 const 前说明符 std::string 作为无序映射键。

    #include <unordered_map>
    #include <utility>
    #include <string>
    #include <iostream>
    
    int main()
    {
    
        int myint = 5;
        std::unordered_map<const std::string, int*> map;
        map.insert({"string", &myint});
        std::cout << *map.at("string") << std::endl;
    
        return 0;
    }
    

    为什么这段代码在 const std::string 在以下情况下用作键: 字符串 作品

    1 回复  |  直到 8 年前
        1
  •  4
  •   NathanOliver    5 年前

    std::unordered_map 使用 std::hash 默认情况下,用于哈希函数。它使用键的类型作为 散列 . <string> 专门研究 散列 对于 std::string 但是由于密钥类型是 const std::string ,没有匹配的专门化,编译失败。


    但实际上,使用 std::unordered_map<std::string, int*> 你需要什么就做什么。所有关联容器中的键都是 const 已经为你准备好了,所以没有理由参加 常数 在模板参数中。