Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Insert or Update a Map

📅 2011-Jan-11 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, insert, maps, stl ⬩ 📚 Archive

A C++ STL map is used to store and manage key-value pairs. The elements are maintained in the sorted order of the keys. The keys in a map cannot be changed. Either a new key-value pair can be added or the value of an already existing key-value pair can be changed. These operations are supported by 2 interfaces: insert() and the subscript operator []. These 2 interfaces differ slightly and it is important to be aware how since it has implications on correctness and efficiency.

Consider a map:

#include <map>
using namespace std;

typedef map<KeyType, ValType> KVMap;

KVMap kvmap;

To insert a new key-value pair to the map use:

kvmap.insert( KVMap::value_type( key0, val0 ) );

It is important to note that if key0 already exists in the map, this operation silently fails, returning a bool value of false! This might seem obvious, put another way, the insert operation cannot be used to update an element of the map.

If the key does not already exist in the map, this is the most convenient and most efficient method to insert a key-value pair into the map.

To update the value of an existing element of the map, use the subscript operator:

kvmap[ key0 ] = val1;

This interface is very convenient, but the user needs to be acutely aware of how this works:

  1. The subscript operator [] uses the key0 to search for that element in the map. If the element exists, a reference to its value is returned. If the element does not exist, a new element with the given key and a value constructed using the default constructor is used.

  2. The assignment operator assigns the value to the reference returned by the subscript operator [].

What all of this means is that the subscript operator is both convenient and efficient to update the value of an already existing element in the map. Since the value is constructed by default once and then assigned again, it is not an efficient way to insert a key-value pair to the map!

The subscript operator can be dangerous when used without assigning any value! If the map does not have an element with key99, the following statement creates a new element with key99 in the map:

kvmap[ key99 ];
// or ...
cout << kvmap[ key99 ];

Inserting and updating elements in a map has these few potholes, so drive carefully when using them! 😁