从const unordered_map读取对象 [英] reading object from const unordered_map

查看:181
本文介绍了从const unordered_map读取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不允许从常量unordered_map中读取对象?

  const unordered_map< int,int> z; 
int val = z [5]; // compile error

clang下面的错误如下:

 错误:没有可行的重载操作符[]类型为'const 
unordered_map< int,int>'
int val = z [5]

考虑到使用 const向量的等效代码工作正常我有点困惑为什么我们得到这个行为。

解决方案 c> ] 调用地图的非const成员函数。



这是因为地图的 operator [] 将会插入一个新的元素,如果没有找到的键,所以显然它必须是非const。



对于 vector 操作符[] 中没有插入任何内容,该元素必须已经存在(或者您获得未定义的行为,所以等效代码将访问第6



要查找未添加的键,请使用:

  int val = 0; 
auto it = z.find(5);
if(it!= z.end())
val = it-> second;


Why am I not allowed to read an object from a constant unordered_map?

const unordered_map<int, int> z;
int val = z[5]; // compile error

The error under clang is the following:

error: no viable overloaded operator[] for type 'const
      unordered_map<int, int>'
                        int val = z[5];

Considering that the equivalent code using a const vector works fine I'm somewhat confused why we get this behavior.

解决方案

The expression z[5] calls a non-const member function of the map.

This is because a map's operator[] will insert a new element if the key isn't found, so obviously it has to be non-const.

For a vector nothing is inserted by operator[], the element must exist already (or you get undefined behaviour, so the equivalent code would access the 6th element of an empty vector, which is not fine!).

To lookup a key without adding it use:

int val = 0;
auto it = z.find(5);
if (it != z.end())
  val = it->second;

这篇关于从const unordered_map读取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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