unordered_map operator[] in C++ STL

The std::unordered_map::operator[] is a built in function in C++ STL which returns the reference of value if key matches in the container. If no key is found then it inserts that key into container.
Syntax:

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

Parameter: It takes parameter as key whose mapped value is accessed.
Return type: Returns a reference associated to that key.

Example 1



filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code to illustrate the method
// unordered_map operator[]
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    unordered_map<int, int> sample;
  
    // Map initialization
    sample = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
  
    // print element before doing
    // any operations
    for (auto& it : sample)
        cout << it.first << " : " << it.second << endl;
  
    // existing element is read
    int m = sample[1];
  
    // existing element is written
    sample[3] = m;
  
    // existing elements are accessed
    sample[5] = sample[1];
  
    // non existing element
    // new element 25 will be inserted
    m = sample[25];
  
    // new element 10 will be inserted
    sample[5] = sample[10];
  
    // print element after doing
    // operations
    for (auto& it : sample)
        cout << it.first << " : " << it.second << endl;
    return 0;
}

chevron_right


Output:

5 : 6
3 : 4
1 : 2
10 : 0
1 : 2
5 : 0
3 : 2
25 : 0

Example 2

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code to illustrate the method
// unordered_map operator[]
#include <bits/stdc++.h>
  
using namespace std;
  
int main()
{
    unordered_map<char, int> sample;
  
    // Map initialization
    sample = { { 'a', 2 }, { 'b', 4 }, { 'c', 6 } };
  
    // print element before doing
    // any operations
    for (auto& it : sample)
        cout << it.first << " : " << it.second << endl;
  
    // existing element is read
    int m = sample['a'];
  
    // existing element is written
    sample['b'] = m;
  
    // existing elements are accessed
    sample['c'] = sample['a'];
  
    // non existing element
    // new element 'd' will be inserted
    m = sample['d'];
  
    // new element 'f' will be inserted
    sample['c'] = sample['f'];
  
    // print element after doing
    // operations
    for (auto& it : sample)
        cout << it.first << " : " << it.second << endl;
    return 0;
}

chevron_right


Output:

c : 6
b : 4
a : 2
f : 0
a : 2
b : 2
c : 0
d : 0

Time Complexity O(n) in worst case.



My Personal Notes arrow_drop_up

Let the code do the talking

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.