【问题标题】:Why does std::unordered_map not work with const std::string key?为什么 std::unordered_map 不能与 const std::string 键一起使用?
【发布时间】:2018-05-29 21:11:15
【问题描述】:

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

#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 用作键时这段代码不编译,而std::string 有效?

【问题讨论】:

  • @NO_NAME 重复错误
  • 这有什么意义?映射中的键是原始字符串的副本。
  • @Barmar 要明确吗?
  • 我想知道为什么mapunordered_map 在这方面有所不同。很遗憾,副本似乎没有解决这个问题。
  • @NO_NAME 因为它没有回答提出的问题:为什么它不编译

标签: c++ unordered-map


【解决方案1】:

std::unordered_map 默认使用std::hash 作为哈希函数。它使用模板类型std::hash 的键类型。 &lt;string&gt;std::hash 特化为 std::string 但由于键类型为 const std::string,因此没有匹配的特化并且编译失败。


确实,使用std::unordered_map&lt;std::string, int*&gt; 将完全满足您的需求。所有关联容器中的键都是const,因此没有理由在模板参数中标记const

【讨论】:

  • 这是一个“错误”吗?
  • @user3728501 在哪里?
  • @user3728501 这不是代码错误。您可能将其称为语言错误(标准应该说需要有一个 const 版本),但由于关联容器中的键是 const 的,因此实际上并不需要。 std::unordered_map&lt;std::string, int*&gt; 将做完全相同的事情并实际编译。
  • @SergeyA 为什么世界上每个希望将 const 说明符放在那里的开发人员也实现自己的哈希函数?
  • 世界上的每个开发者都会思考“为什么”他们想要这样做,却发现没有充分的理由?
猜你喜欢
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 2012-01-17
相关资源
最近更新 更多