map::operator[] in C++ STL Last Updated : 09 Jan, 2023 Comments Improve Suggest changes 15 Likes Like Report 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. map::operator[] 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 inserts a new element with that key and returns a reference to its mapped value, increasing the container size by one, the element is constructed using its default constructor if no value is provided.Syntax : mapname[key] Parameters : Key value mapped to the element to be fetched. Returns : Direct reference to the element at the given key value. Examples: Input : map mymap; mymap['a'] = 1; mymap['a']; Output : 1 Input : map mymap; mymap["abcd"] = 7; mymap["abcd"]; Output : 7 CPP // CPP program to illustrate // Implementation of [] operator #include <iostream> #include <map> #include <string> 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] is " << mymap[4] << '\n'; // using operator[] to access the key is not in the map // it displays the default value in the constructor cout << "mymap[5] is " << mymap[5] << '\n'; // the map size increases to 5 cout << "mymap now contains " << mymap.size() << " elements.\n"; return 0; } Outputmymap[4] is GeeksForGeeks mymap[5] is mymap now contains 5 elements. Time Complexity: O(logn) Create Quiz Comment A AyushSaxena Follow 15 Improve A AyushSaxena Follow 15 Improve Article Tags : Misc C++ STL cpp-map Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like