对 unordered_map 使用 const 键

2024-08-14C/C++开发问题
6

本文介绍了对 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 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6