C++ Map : Operator [] – Usage Details

In the previous article, we have discussed about C++ std::set example and tutorial with external sorting criteria | Comparator. Let us learn map operator in C++ Program.

C++ Map : Operator [] :

In this article, we will learn to use operator ‘[ ]’ in C++.

  • std::operator provides the Operator [ ] which has the following syntax,
   mapped_type& operator[] (const key_type& k);
  • The operator [ ] works in find or create Mode i.e. when we call with a key K, it will search for element in key K and can go in any of the two directions i.e.
  • If any element has key K, the reference value will be returned for that value.
  • But if no element found with key K, a new element will be created in map with key K to which a default value of value_type will be assigned to its value field. So, as a reference it will return the value of newly created element.

Table of content:

Element lookup with Operator[] :

Suppose, we have a map of String and Int type, means string as key and int as value.

// Map of string & int
// occurrence count as values
std::map<std::string, int> magMap =
 {
                    { "Dynamo", 9 },
                    { "Blaine", 8 },
                    { "Houdini", 7 },
                    { "Teller", 6 }
};

Now if we call Operator [ ] on the map with “Apollo” key, a new entry will be created by operator [ ] as “Apollo” key is not present in map. And a default value of int will be assigned which in this case is 0.

Let’s see the below program.

#include <iostream>
#include <map>
#include <string>

int main(){
    
// Map of string & int 
// occurrence count as values
std::map<std::string, int> magMap = {
                    { "Dynamo", 9 },
                    { "Blaine", 8 },
                    { "Houdini", 7 },
                    { "Teller", 6 }
                };
                
// since no element with key 'Hello' operator [] will create a new element in map
// new element will have key value as "Apollo" and a default value
int & temp = magMap ["Apollo"];   
std::cout<<"Value of key 'Hello' = "<<temp<<std::endl;

}
Output :
Value of key 'Hello' = 0

Overriding values with operator [] :

We can assign value by calling operator [ ] which will change the value. Since operator [ ] return value by reference so it will override with new value.

Let’s see a program to understand it.

#include <iostream>
#include <map>
#include <string>

int main(){
    
// Map of string & int 
// occurrence count as values
std::map<std::string, int> magMap = {
                    { "Dynamo", 9 },
                    { "Blaine", 8 },
                    { "Houdini", 7 },
                    { "Teller", 6 }
                };
                
// since no element with key 'Hello' operator [] will create a new element in map
// new element will have key value as "Apollo" and a default value
int & temp = magMap ["Apollo"]; 
magMap["Teller"] = 40;
int & temp2 = magMap["Teller"];
std::cout<<"value of key 'Teller' = "<<temp2<<std::endl;

}
Output :

value of key 'Teller' = 40

Complete program :

#include <iostream>
#include <map>
#include <string>

int main(){
    
// Map of string & int 
// occurrence count as values
std::map<std::string, int> magMap = {
                    { "Dynamo", 9 },
                    { "Blaine", 8 },
                    { "Houdini", 7 },
                    { "Teller", 6 }
                };
                
// since no element with key 'Hello' operator [] will create a new element in map
// new element will have key value as "Apollo" and a default value
int & temp = magMap ["Apollo"]; 
magMap["Teller"] = 40;
int & temp2 = magMap["Teller"];
std::cout<<"value of key 'Teller' = "<<temp2<<std::endl;

    std::cout<< "\n------------Map--------------" <<std::endl;
    // Print the elements of map
    for (auto ele : magMap)
        std::cout << ele.first << " :: " << ele.second << std::endl;

}
Output :

value of key 'Teller' = 40


------------Map--------------

Apollo :: 0

Blaine :: 8

Dynamo :: 9

Houdini :: 7

Teller :: 40

Using operator[] with User Defined objects as Value :

If we are using user defined class or struct as value then it must have a default constructor as operator [ ] creates new entry with default value. If we do so our program will be successfully compiled.

#include <iostream>
#include <map>
#include <string>

struct Greats
{
    int var;
    // Default Constructor
    Greats()
    {
        this->var = 0;
    }
    //Parameterized constructor
    Greats(int var)
    {
        this->var = var;
    }
};

int main(){
    
// Map of string & int 
// occurrence count as values
std::map<std::string, Greats> magMap = {
                    { "Dynamo", Greats(9) },
                    { "Blaine", Greats(8) },
                    { "Houdini", Greats(7) },
                    { "Teller", Greats(6) }
                };
                
    // as key not present in map, new entry will be created
    // Due to presence of default value of value field 
    // If it has a default constructor then it will compile
    Greats con = magMap["Apollo"];
    
    return 0;

}

This program compiled successfully.