C++ unordered_map operator[]
Example
Add a new element, and change the value of an existing key:
unordered_map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
people["Jenny"] = 22; // Add a new element
people["John"] = 50; // Change the value of John
cout << "Jenny is: " << people["Jenny"] << "\n";
cout << "John is: " << people["John"];
Definition and Usage
The [] operator (square brackets) gives you the value of the element with the given key, so you can read or change it.
If the key does not exist, a new element is added with that key and a default value, like 0 for an int. This also happens when you only read the value.
The operator[] is defined in the <unordered_map> header file.
Tip: Use at() or count() if you do not want to add a new element by mistake.
Syntax
unordered_map[key]
Parameter Values
| Parameter | Description |
|---|---|
| key | Required. The key of the element to get, change or add. |
Technical Details
| Returns: | A reference to the value of the element, so you can read or change it. |
|---|
Related Pages
Read more about unordered maps in our Unordered Map Tutorial.