C++ Standard Library C++ STL Library

C++ unordered_map - operator[]() Function



The C++ unordered_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 unordered_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 unordered_map::at, except unordered_map::at throws an out_of_range exception if the specified key does not match with key of any element of the unordered_map.

Syntax

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

Parameters

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

Return Value

The element at the specified position in the unordered_map.

Time Complexity

Average case: constant.
Worst case: Linear in container size.

Example:

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

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

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

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

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

  return 0;
}

The output of the above code will be:

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

❮ C++ <unordered_map> Library