c++ - STL Map 是否自动初始化值?

标签 c++ stl map

Possible Duplicate:
Why does a class used as a value in a STL map need a default constructor in …?

当我使用 map 时,值肯定会被初始化为默认值还是我不应该依赖这个?

例如,假设我有以下代码:

map<string, int> myMap;
cout << myMap["Hey"];

这将使用我的编译器输出“0”。这是有保证的行为吗?这可能不会总是初始化为 0?

最佳答案

标准:

ISO/IEC 14882 §23.4.4.3

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.

因此,不仅可以保证,如果没有条目,评估 myMap["Hey"] 还会导致值 0 插入到 map 中之前的。

关于c++ - STL Map 是否自动初始化值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12889496/

相关文章:

c++ - 当 dns 启动和关闭时,curl apis 不会更改值,但 curl 命令给出成功/失败输出

c++ - 为什么它打破了初始化列表的顺序规则时会起作用

c++ - 使用 STL vector 管理 opengl 缓冲区对象

java - 获取内存(RAM)上的 map 大小

c++ - 在 C++ 中创建 lambda 映射

api - 政治边界 map 类似于谷歌图表, "clickable"个国家

c# - 从 C#(紧凑型框架)访问 VC++ Dll

c++ - 复合模板

c++ - llvm-gcc std::allocator 错误?

c++ - 如何让STL映射仅构造/破坏插入的对象一次