map::operator[] in C++ STL Program


In this article we will be discussing the working, syntax and example of map equal ‘[]’ operator in C++ STL.

What is a Map in C++ STL?

Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.

What is a map equal to ‘[]’ operator?

map::operator[] is a reference operator. This operator is used to access the element in the container by its key.

If there is no key matching in the container, then the operator inserts a new element with that key and returns the reference of the mapped value. This operator works the same as the map::at(), the only difference is that at() throws an exception when the key is not present in the map container.

Syntax

Map_name[key& k];

Parameter

There is only 1 parameter i.e. the key k which we want to reference in the container.

Return value

This operator returns the value associated to the key k.

Input

map<char, int> newmap;
newmap.insert({1, 20});
newmap.insert({2, 30});
newmap[1];

Output 

20

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   map<int, int> TP_1;
   map<int, int> TP_2;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   cout<<"Element at TP[3] is : "<<TP_1[3];
   return 0;
}

Output

If we run the above code it will generate the following output −

Element at TP[3] is : 30

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   map<int, int> TP_1;
   map<int, int> TP_2;
   TP_1[1] = 10;
   TP_1[2] = 20;
   TP_1[3] = 30;
   TP_1[4] = 40;
   cout<<"Element at TP[3] is : "<<TP_1[3];
   if(TP_1[5]==0){
      cout<<"\nElement at TP[5] doesn't exist";
   }
   else{
      cout<<"Element at TP[5] is : "<<TP_1[5];
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

Element at TP[3] is : 30
Element at TP[5] doesn't exist

Updated on: 14-Aug-2020

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements