Skip to content
Related Articles

Related Articles

Improve Article

map::operator[] in C++ STL

  • Difficulty Level : Medium
  • Last Updated : 18 Jan, 2018

Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.


This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of map, while this operator causes undefined behaviour.

Syntax :

Parameters :
Key value mapped to the element to be fetched.
Returns :
Direct reference to the element at the given key value.


Input  :  map mymap;
          mymap['a'] = 1;
Output :  1

Input  :  map mymap;
          mymap["abcd"] = 7;
Output :  7

Errors and Exceptions

1. If the key is not present in the map, it shows undefined behaviour.
2. It has a no exception throw guarantee otherwise.

// CPP program to illustrate
// Implementation of [] operator
#include <map>
#include <iostream>
using namespace std;
int main()
    // map declaration
    map<int,string> mymap;
    // mapping integers to strings
    mymap[1] = "Hi";
    mymap[2] = "This";
    mymap[3] = "is";
    mymap[4] = "GeeksForGeeks";
    // using operator[] to print string 
    // mapped to integer 4
    cout << mymap[4];
    return 0;



Time Complexity: O(logn)

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :