对 unordered_map 使用 const 键

Using a const key for unordered_map(对 unordered_map 使用 const 键)
本文介绍了对 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, 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.

这篇关于对 unordered_map 使用 const 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)