如果我在键不存在的情况下读取地图的值会发生

What happens if I read a map#39;s value where the key does not exist?(如果我在键不存在的情况下读取地图的值会发生什么?)
本文介绍了如果我在键不存在的情况下读取地图的值会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

map<string, string> dada;
dada["dummy"] = "papy";
cout << dada["pootoo"];

我很困惑,因为我不知道它是否被认为是未定义的行为,如何知道我何时请求不存在的密钥,我是否只使用 find ?

I'm puzzled because I don't know if it's considered undefined behaviour or not, how to know when I request a key which does not exist, do I just use find instead ?

推荐答案

map::operator[] 在数据结构中搜索与给定键对应的值,并返回对它的引用.

The map::operator[] searches the data structure for a value corresponding to the given key, and returns a reference to it.

如果它找不到一个,它会透明地为它创建一个默认的构造元素.(如果您不想要这种行为,您可以改用 map::at 函数.)

If it can't find one it transparently creates a default constructed element for it. (If you do not want this behaviour you can use the map::at function instead.)

您可以在此处获取 std::map 方法的完整列表:

You can get a full list of methods of std::map here:

http://en.cppreference.com/w/cpp/container/map

这是当前 C++ 标准中 map::operator[] 的文档...

Here is the documentation of map::operator[] from the current C++ standard...

  1. 效果:如果映射中没有与 x 等效的键,则将 value_type(x, T()) 插入映射中.

  1. Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.

要求:key_type 应为 CopyConstructible,mapped_type 应为 DefaultConstructible.

Requires: key_type shall be CopyConstructible and mapped_type shall be DefaultConstructible.

返回:对 *this 中 x 对应的映射类型的引用.

Returns: A reference to the mapped_type corresponding to x in *this.

复杂度:对数.

T&运算符[](key_type&& x);

  1. 效果:如果映射中没有与 x 等效的键,则将 value_type(std::move(x), T()) 插入映射中.

  1. Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.

要求:mapped_type 应为 DefaultConstructible.

Requires: mapped_type shall be DefaultConstructible.

返回:对 *this 中 x 对应的映射类型的引用.

Returns: A reference to the mapped_type corresponding to x in *this.

复杂度:对数.

这篇关于如果我在键不存在的情况下读取地图的值会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

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?(易失性成员变量与易失性对象?)