Bos*_*ash -1 c++ unordered-map
我有一个无序的地图,使用指向自定义对象的指针作为键.出于某种原因,只有在键不是const的情况下才能使用键查找值.
这是一个示例(std::string作为自定义对象的替代):
std::unordered_map<std::string*, int> my_map;
std::string key {"test"};
const std::string const_key {"test2"};
auto value = my_map.at(&key); // this works as expected
auto other_value = my_map.at(&const_key); // this doesn't compile
error: invalid conversion from 'const string* {aka const std::__cxx11::basic_string<char>*}'
to 'std::unordered_map<std::__cxx11::basic_string<char>*, int>::key_type
{aka std::__cxx11::basic_string<char>*}' [-fpermissive]
Run Code Online (Sandbox Code Playgroud)
为什么查找要求指针为非const?
当你写&const_key这个评估结果时const std::string *,你的地图std::string *用作关键字类型.
"地址到字符串"和"地址到字符串是const"之间有区别.因此,这些被认为是不同的类型,您不能互换使用它们.
PS无法将其写为评论,因此发布为答案.