The unordered_map::at()
function is available in the <unordered_map>
header file in C++.
The unordered_map::at()
function is used to obtain the reference to the mapped value of the element with the equivalent key. If the key is not present in the map, then the function throws an exception.
The syntax of the unordered_map::at()
function is given below:
V at(K key);
Key
: The key whose mapped value we want to be retrieved.Value
: The reference to the mapped value of the element with the equivalent key.Let’s take a look at the code.
#include <iostream>#include <unordered_map>using namespace std;int main(){unordered_map<int, string> umap ={{12,"unordered"},{16,"map"},{89,"in"},{66,"C++"}};cout<<"Value present in the map for key = 16 is: " << umap.at(16);cout << endl;umap[16] = "Modified";for(auto& m: umap)cout << m.first << ", " << m.second << endl;return 0;}
In lines 1 and 2: We import the required header files.
In line 5: We make a main()
function.
In lines 7 to 11: We initialize an unordered_map
with integer type keys and string type values.
In line 13: We use the unordered_map::at()
function to obtain the mapped value of the key in the parameter and display the result with a message.
In line 16: We use the unordered_map::at()
function to modify the specified key value.
In lines 17 and 18: We print the key-value pairs present in the unordered map.
So, this is the way to use the unordered_map::at()
function to get the specified key’s value or even update the value of existing keys in C++.