问题描述
map< string,string>达达;
dada [dummy] =papy;
cout<<<达达[ pootoo];
我很困惑,因为我不知道是否被认为是未定义的行为,如何知道当我要求一个不存在的密钥时,我是否只使用find?
:: operator []
在数据结构中搜索与给定键对应的值,并返回一个引用。
如果可以不能找到它透明地为它创建一个默认的构造元素。 (如果你不想要这个行为,你可以使用 map :: at
函数。)
你可以在这里获取std :: map的完整列表:
这里是 map :: operator []
从当前的C ++标准...
23.4.4.3地图元素访问
T&运算符[](const key_type& x);
-
效果:如果没有键等效到地图中的x,将value_type(x,T())插入到地图中。
-
需要:key_type应为CopyConstructible,mapped_type应为DefaultConstructible。 / p>
-
返回:对* this中对应于x的mapped_type的引用。
-
复杂性:对数。
T&运算符[](key_type&& x);
-
效果:如果没有键相当于地图中的x,将value_type(std :: move(x),T())插入到地图中。
-
需要:mapped_type应为DefaultConstructible
-
返回:对* this中对应于x的mapped_type的引用。
-
复杂性:对数。
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);
Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
Requires: key_type shall be CopyConstructible and mapped_type shall be DefaultConstructible.
Returns: A reference to the mapped_type corresponding to x in *this.
Complexity: logarithmic.
T& operator[](key_type&& x);
Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.
Requires: mapped_type shall be DefaultConstructible.
Returns: A reference to the mapped_type corresponding to x in *this.
Complexity: logarithmic.
这篇关于如果我看到地图的值不存在的话,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!