C++ unordered_map at() Function
Example
Get the value of the element with the key "Adele":
unordered_map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
cout << "Adele is: " << people.at("Adele");
Definition and Usage
The at() function returns the value of the element with the given key.
If the key does not exist, at() throws an out_of_range exception (an error that stops the program if you do not handle it). This makes it safer than square brackets [], which add a new element when the key does not exist.
The at function is defined in the <unordered_map> header file.
Tip: You can also use at() to change a value, like people.at("Adele") = 50;.
Syntax
unordered_map.at(keyType key)
keyType is the type of the keys in the unordered map, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| key | Required. The key of the element to get. |
Technical Details
| Returns: | A reference to the value of the element, so you can read or change it. If the key does not exist, an out_of_range exception is thrown. |
|---|
Related Pages
Read more about unordered maps in our Unordered Map Tutorial.