对 unordered_map 使用 const 键

2022-01-07 00:00:00 c++ stl

我一直在适当的地方将我的代码从 std::map 切换到 std::unordered_map.使用 std::map,我通常会编写以下内容以确保无法修改密钥:

I've been switching my code over from std::map to std::unordered_map where appropriate. With std::map, I typically write the following just to make sure the key cannot be modified:

std::map<const std::string, int>

坦率地说,我从来没有检查过这个 const 是否有任何价值.这一直与 g++ 一起编译和工作.

Frankly, I never checked if this const was of any value. This has always compiled and worked with g++.

现在,使用 std::unordered_map,以下内容无法与 g++ 4.5.1 链接.

Now, with std::unordered_map, the following fails to link with g++ 4.5.1.

std::unordered_map<const std::string, std::string> m;
m["foo"] = "bar";

出现此链接错误:

未定义的符号:"std::hash<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const>::operator()(std::basic_string<char, std::char_traits, std::allocator >) const",引用自:

Undefined symbols: "std::hash<std::basic_string<char, std::char_traits<char>, std::allocator<char> > const>::operator()(std::basic_string<char, std::char_traits<char>, std::allocator<char> >) const", referenced from:

修复很简单,删除const,但除此之外,在STL中是否有任何关联容器类使用const键类型的点?没有任何方法可以让您获得对任何关联容器的键的引用吗?

The fix is simple, to remove const, but besides that, is there even a point in STL with any of the associative container classes to use a const key type? Are there no methods that let you get a reference to the key for any associative container?

推荐答案

关联容器仅将 (key,value) 对暴露为 std::pair,因此键类型上的额外常量是多余的.

The associative containers only expose the (key,value) pair as std::pair<const key_type, mapped_type>, so the additional const on the key type is superfluous.

相关文章