C++ 为什么std::unordered_映射不能与const std::string键一起工作?
下面的代码示例不会编译,但是可以通过删除C++ 为什么std::unordered_映射不能与const std::string键一起工作?,c++,unordered-map,C++,Unordered Map,下面的代码示例不会编译,但是可以通过删除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
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;
}
#包括
#包括
#包括
#包括
int main()
{
int-myint=5;
std::无序地图;
insert({“string”,&myint});
std::coutstd::unordered_map
默认情况下使用std::hash
作为哈希函数的模板类型。它使用键的类型作为std::hash
作为std::string
的模板类型,但由于键的类型是const std::string
,因此没有匹配的特殊项优化和编译失败
实际上,使用std::unordered_map
将完全满足您的需要。所有关联容器中的键都是const
,因此没有理由在模板参数中标记const
。@no\u NAME错误重复这有什么意义?映射中的键是原始字符串的副本。@Barmar是否明确?我想知道为什么map
和unordered\u map
在这方面有所不同。遗憾的是,副本似乎没有解决这个问题。@SergeyA为什么?它指的是完全相同的问题。这是一个“bug”?@user3728501在哪里?@user3728501它不是一个代码bug。你可以称之为语言bug(标准应说明需要一个常量版本)但是,由于关联容器中的键是常量,所以实际上并不需要它。std::unordered_map
将执行完全相同的操作并实际编译。@SergeyA为什么世界上每个希望将常量说明符放在那里的开发人员都会实现自己的哈希函数?世界上每个开发人员都会想到“为什么”t嘿,你想这么做,却发现没有什么好的理由?