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?
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 .
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().
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.
Duplicate keys are not allowed in a Map.
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 objectdata_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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With