STL Map自动初始化值吗? [英] Does STL Map auto-initialize values?

查看:391
本文介绍了STL Map自动初始化值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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


  1. 效果:在地图中不等价于 x 的关键字,将 value_type(x,T())插入到地图中。 / li>
  2. 需要: key_type 应为 CopyConstructible mapped_type 应为 DefaultConstructible

  3. 返回: x mapped_type 的引用, *

  4. 复杂性:对数。

  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.


所以,不仅保证了,而且评估 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屋!

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