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

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

问题描述

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

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

解决方案

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



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



你可以在这里获取std :: map的完整列表:



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



这里是 map :: operator [] 从当前的C ++标准...



23.4.4.3地图元素访问



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




  1. 效果:如果没有键等效到地图中的x,将value_type(x,T())插入到地图中。


  2. 需要:key_type应为CopyConstructible,mapped_type应为DefaultConstructible。 / p>


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


  4. 复杂性:对数。




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




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


  2. 需要:mapped_type应为DefaultConstructible


  3. 返回:对* this中对应于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天全站免登陆