Mayank Jain Mayank Jain - 1 month ago 38
C++ Question

Operator[] in std::map implementation

I am trying to implement a container like std::map in C++. I have a small query while overloading operator []. I see that this operator works in two ways:


  1. mymap[2]
    - For this case it looks for key 2 in map and return the value against this key.

  2. mymap[2]=3
    - For this case it looks for key 2 in map and if key is not found than 3 is inserted in map.



I see that declaration for this operator looks like:
Mapped_T &operator[](const Key_T &);
but what I am not getting is that in case the key is not found I will have to insert a new element in Map but in declaration of operator[] function I don't see value being passed anywhere. So how would overloaded operator know what is value against key to be inserted?

Answer

When the key does not exist, std::map constructs a new value using the value class's default constructor, and returns a reference to the newly-inserted value.