1) When calling operator [] with a key (index) which doesn't exist in the map, a new key-value pair gets inserted into the map automatically.
std::map<std::string,float> coll; // empty map
cout << coll["hello"] << endl; // "hello" key doesn't exist in the map, pair<const string, float>("hello", 0) get inserted into the map automatically. This usually is not what we want.
2) What is happening underneath for "coll["otto"] = 7.7;" ? (It is a little bit slow !)
a) Process coll["otto"] expression:
- If an element with key "otto" exists, the expression returns the value of the element by reference
- If, as in this example, no element with key "otto" exists, the expression inserts a new element
automatically, with "otto" as key and the value of the default constructor of the value type as
the element value. It then returns a reference to that new value of the new element.
b) Assign value 7.7:
- The second part of the statement assigns 7.7 to the value of the new or existing element.