Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the STL map[key] return if the key wasn't a initialized key in the map? [duplicate]

Tags:

c++

map

stl

Here is some example code:

 #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;  } 

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

like image 704
Mirza Avatar asked Feb 23 '11 04:02

Mirza


People also ask

What does map return if key does not exist?

The map contains this key . So it will return the corresponding key value . The map doesn't contain the key . In this case, it will automatically add a key to the map with null value .

What does map return if key not found CPP?

map find() function in C++ STL Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map. end().

What will happen if we insert duplicate key in map C++?

a map will not throw any compile/run time error while inserting value using duplicate key. but while inserting, using the duplicate key it will not insert a new value, it will return the same exiting value only. it will not overwrite. but in the below case it will be overwritten.

Can you have duplicate values in a map C++?

Duplicate keys are not allowed in a Map.


1 Answers

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

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

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().

(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.)

like image 142
James McNellis Avatar answered Sep 25 '22 19:09

James McNellis