tags:

views:

501

answers:

4

What is the difference between the index overloaded operator and the insert method call for std::map?

ie:

some_map["x"] = 500;

vs.

some_map.insert(pair<std::string, int>("x", 500));
A: 

The insert method inserts into the map, while the overloaded index operator will return the element with the key key_value if it is in the map, if it is not already in the map then it will insert it.

Brandon Haugen
It'll only insert into the map if a given key is not already present. If it is present, insert() will not update the value whereas an assignment to operator[] will.
Timo Geusch
+9  A: 

I believe insert() will not overwrite an existing value, and the result of the operation can be checked by testing the bool value in the iterator/pair value returned

The assignment to the subscript operator [] just overwrites whatever's there (inserting an entry if there isn't one there already)

Either of the insert and [] operators can cause issues if you're not expecting that behaviour and don't accommodate for it.

Eg with insert:

std::map< int, std::string* > intMap;
std::string* s1 = new std::string;
std::string* s2 = new std::string;
intMap.insert( std::make_pair( 100, s1 ) ); // inserted
intMap.insert( std::make_pair( 100, s2 ) ); // fails, s2 not in map, could leak if not tidied up

and with [] operator:

std::map< int, std::string* > intMap;
std::string* s1 = new std::string;
std::string* s2 = new std::string;
intMap[ 100 ] = s1; // inserted
intMap[ 100 ] = s2; // inserted, s1 now dropped from map, could leak if not tidied up

I think those are correct, but haven't compiled them, so may have syntax errors

pxb
+5  A: 

For a map, the former (operator[]) expression will always replace the value part of the key-value pair with the new supplied value. A new key-value pair will be inserted if one doesn't already exist.

In contrast, insert will only insert a new key-value pair if a key-value pair with the supplied key part does not already exist in the map.

Charles Bailey
+3  A: 

In addition to the fact that map::operator[] will replace an existing value is that operator[] map::will create and add to the map a default existing value to replace before the replacement occurs (the map::operator[]() call has to return a reference to something). For items that are expensive to create this could be a performance issue.

See "Item 24: Choose carefully between map::operator[] and map::insert when efficiency is important" in Scott Meyers' Effective STL.

Michael Burr