insert
is not a recommended way - it is one of the ways to insert into map. The difference with operator[]
is that the insert
can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert
. operator[]
needs the default constructor because the map checks if the element exists. If it doesn't then it creates one using default constructor and returns a reference (or const reference to it).Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.