In this article we will be discussing the working, syntax and example of map equal ‘[]’ operator 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.
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.
Map_name[key& k];
There is only 1 parameter i.e. the key k which we want to reference in the container.
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];
20
#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; }
If we run the above code it will generate the following output −
Element at TP[3] is : 30
#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; }
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