C++ Standard Library C++ STL Library

C++ map - operator[]() Function



The C++ map::operator[] function returns a reference to the mapped value of the specified key. If the specified key does not match with key of any element of the map, the function inserts a new element with that key and returns a reference to its mapped value.

Note: This function produces the same result as map::at, except map::at throws an out_of_range exception if the specified key does not match with key of any element of the map.

Syntax

mapped_type& operator[] (const key_type& k);
mapped_type& operator[] (const key_type& k);
mapped_type& operator[] (key_type&& k);

Parameters

k Specify key value of the element in the map whose mapped value is accessed.

Return Value

The element at the specified position in the map.

Time Complexity

Logarithmic i.e, Θ(log(n)).

Example:

In the example below, the map::operator[] function is used to get the mapped value of the specified key in MyMap.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<int, string> MyMap;
  map<int, string>::iterator it;

  //populating MyMap
  MyMap[101] = "John";
  MyMap[102] = "Marry";
  MyMap[103] = "Kim";

  //changing the mapped value for key=103
  MyMap[103] = "Ramesh";

  //accessing mapped value of specified key
  cout<<"MyMap[101] = "<<MyMap[101]<<"\n";
  cout<<"MyMap[102] = "<<MyMap[102]<<"\n";
  cout<<"MyMap[103] = "<<MyMap[103]<<"\n";
  cout<<"MyMap[104] = "<<MyMap[104]<<"\n";
  cout<<"MyMap[105] = "<<MyMap[105]<<"\n";

  return 0;
}

The output of the above code will be:

MyMap[101] = John
MyMap[102] = Marry
MyMap[103] = Ramesh
MyMap[104] = 
MyMap[105] = 

❮ C++ <map> Library