Using a const key for unordered_map(对 unordered_map 使用 const 键)
问题描述
我一直在适当的地方将我的代码从 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,引用自:
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.
这篇关于对 unordered_map 使用 const 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对 unordered_map 使用 const 键
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
