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);
- 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 插入到 map 中之前的。
关于c++ - STL Map 是否自动初始化值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12889496/