如果键不是映射中的初始化键,则STL映射[键]返回什么?

如果键不是映射中的初始化键,则STL映射[键]返回什么?

问题描述:

以下是一些示例代码:

 #include<iostream>
 #include<map>
 #include<string>
 using namespace std;

 int main()
 {
   map<char, string> myMap;
   myMap['a'] = "ahh!!";
   cout << myMap['a'] << endl << myMap['b'] << endl;
   return 0;
 }

在这种情况下,我想知道myMap ['b']返回什么?

In this case i am wondering what does myMap['b'] return?

默认构造的 std :: string code> code> std :: map ,并返回'b'的引用。

A default constructed std::string ins inserted into the std::map with key 'b' and a reference to that is returned.

请参阅文档,它定义了 operator [] as:

It is often useful to consult the documentation, which defines the behavior of operator[] as:


返回与特定键。如果映射没有包含这样的对象, operator [] 插入默认对象 data_type() p>

Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object, operator[] inserts the default object data_type().

(SGI STL文档不是C ++标准库的文档,但它仍然是一个无价的资源,因为标准的大多数行为库容器与SGI STL容器的行为相同或非常接近。)

(The SGI STL documentation is not documentation for the C++ Standard Library, but it is still an invaluable resource as most of the behavior of the Standard Library containers is the same or very close to the behavior of the SGI STL containers.)