Recommended way to insert elements into map
insert
is not a recommended way - it is one of the ways to insert into map. The difference withoperator[]
is that theinsert
can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to useinsert
.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.
To quote:
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.
So insert will not change the value if the key already exists, the [] operator
will.
EDIT:
This reminds me of another recent question - why use at()
instead of the [] operator
to retrieve values from a vector. Apparently at()
throws an exception if the index is out of bounds whereas [] operator
doesn't. In these situations it's always best to look up the documentation of the functions as they will give you all the details. But in general, there aren't (or at least shouldn't be) two functions/operators that do the exact same thing.
My guess is that, internally, insert()
will first check for the entry and afterwards itself use the [] operator
.
map[key] = value
is provided for easier syntax. It is easier to read and write.
The reason for which you need to have default constructor is that map[key]
is evaluated before assignment. If key wasn't present in map, new one is created (with default constructor) and reference to it is returned from operator[]
.
Use insert
if you want to insert a new element. insert
will not
overwrite an existing element, and you can verify that there was no
previously exising element:
if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
// Element already present...
}
Use []
if you want to overwrite a possibly existing element:
myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition
This form will overwrite any existing entry.