map::operator[] in C++ STL
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 :
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
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> #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]; return 0; } |
Output:
GeeksForGeeks
Time Complexity: O(logn)
Recommended Posts:
- Conditional or Ternary Operator (?:) in C/C++
- forward_list insert_after() function in C++ STL
- Count of distinct remainders when N is divided by all the numbers from the range [1, N]
- C++ | asm declaration
- Pointers and References in C++
- Implementing Counting Sort using map in C++
- Strings in C++ and How to Create them?
- Enum Classes in C++ and Their Advantage over Enum DataType
- Deque vs Vector in C++ STL
- C++ Programming Basics
- Introduction to C++ Programming Language
- ios manipulators noshowpos() function in C++
- ios rdstate() function in C++ with Examples
- ios operator !() function in C++ with Examples
- ios operator() function in C++ with Examples
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.



