In this article we will discuss how to use operator [] with map in C++.

std::map has Operator[] i.e.

operator [] works in Find or Create Mode i.e. when called with a key K, it will try to look for element with given key K and can go in below 2 directions i.e.

  • If any element is found with key K, then it will return the reference of its value.
  • But if there is no element in map with K, then it will create a new element in map with key K and assign default value of value_type in its value field. Then it will return the value of newly created element as reference.

Let’s discuss it in detail,

Element lookup with Operator[]

Suppose we have a map of String and int i.e.

Now suppose, we call the operator [] on above map with key value ‘Hello’.

As this key ‘Hello’ is not present in map. So operator [] will create a new entry for it with Key ‘Hello’ & Value as default value of int i.e. 0.

Also, will return its value by reference.

Overriding values with operator []

operator [] returns value by reference, so assigning value by calling operator[] can change the value i.e.

Checkout the complete example as follows,


Using operator[] with User Defined objects as Value

As operator[] can create new entry with default value. So, if we are using a User defined class or struct as value in a map, then its must to have default constructor in it.

Let’s see an example,

As key is not in map, so operator[] will create new entry with default value of value field. Therefore, above example will compile only if Occurance struct has default constructor. Un-comment it to compile succussfuly.

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,