STL Map自动初始化值吗? [英] Does STL Map auto-initialize values?
问题描述
Possible Duplicate:
Why does a class used as a value in a STL map need a default constructor in …?
当我使用地图时,值必须初始化为默认值或应该我不依赖这个?
When I'm using a map, do values definitely get initialized to defaults or should I not rely on this?
例如,说我有以下代码:
For example, say I have the following code:
map<string, int> myMap;
cout << myMap["Hey"];
这将与我的编译器输出0。这是保证行为吗?这可能不会总是初始化为0?
This will output "0" with my compiler. Is this guaranteed behavior? Is it possible that this wouldn't always initialize to 0?
推荐答案
标准:
ISO / IEC 14882§23.4.4.3
ISO/IEC 14882 §23.4.4.3
T&运算符[](const key_type& x);
- 效果:在地图中不等价于
x
的关键字,将value_type(x,T())
插入到地图中。 / li>
- 需要:
key_type
应为CopyConstructible
mapped_type
应为DefaultConstructible
。 - 返回:对
x
中
mapped_type
的引用,*
。 - 复杂性:对数。
- Effects: If there is no key equivalent to
x
in the map, insertsvalue_type(x, T())
into the map. - Requires:
key_type
shall beCopyConstructible
andmapped_type
shall beDefaultConstructible
. - Returns: A reference to the
mapped_type
corresponding tox
in*this
. - Complexity: logarithmic.
所以,不仅保证了,而且评估 myMap [Hey]
也会使0被插入该地图,如果以前没有条目。
So, not only is it guaranteed, but evaluating myMap["Hey"]
also causes the value 0 to be inserted into the map, if there was no entry for it before.
这篇关于STL Map自动初始化值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!