如果我读取地图的值,其中键不存在会发生什么? [英] What happens if I read a map's value where the key does not exist?

查看:108
本文介绍了如果我读取地图的值,其中键不存在会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我感到困惑,因为我不知道它是否被认为是未定义的行为,

解决方案

地图:: operator [] 在数据结构中搜索与给定键对应的值,并返回对该键的引用。



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



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



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



这是地图的文档:: operator [] 从当前C ++标准...



23.4.4.3地图元素访问



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





  1. 需要:key_type必须为CopyConstructible,而mapped_type必须为DefaultConstructible。 / p>


  2. 返回:与*中对应的mapped_type的引用。

  3. :对数。




operator [](key_type&& x);




  1. 效果:相当于地图中的x,将VALUE_type(std :: move(x),T())插入到地图中。


  2. 需要:mapped_type应为DefaultConstructible 。


  3. 返回:对应于x中的x的mapped_type的引用。


  4. 复杂性:对数。



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

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 ?

解决方案

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

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.)

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

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

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

23.4.4.3 Map Element Access

T& operator[](const key_type& x);

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

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

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

  4. Complexity: logarithmic.

T& operator[](key_type&& x);

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

  2. Requires: mapped_type shall be DefaultConstructible.

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

  4. Complexity: logarithmic.

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

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