对unordered_map使用const键 [英] Using a const key for unordered_map

查看:477
本文介绍了对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< char>,std :: allocator< char>>)const,引用自:

修复是简单的,要删除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 type?

推荐答案

关联容器只暴露(关联类型)的键,键,值)对作为 std :: pair< const key_type,mapped_type> ,所以键类型上的附加常量是多余的。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆