C++ unordered_map - at() Function
The C++ unordered_map::at function returns a reference to the mapped value of element identified with specified key. If the specified key does not match with key of any element of the unordered_map, the function throws an out_of_range exception.
Note: The unordered_map::at function produces the same result as operator[] function, except operator[] does not throw an out_of_range exception if the specified key does not match with key of any element of the unordered_map.
Syntax
mapped_type& at (const key_type& k); const mapped_type& at (const key_type& k) const;
Parameters
k |
Specify key value of the element in the unordered_map whose mapped value is accessed. |
Time Complexity
Average case: constant.
Worst case: Linear in container size.
Example:
In the example below, the unordered_map::at function is used to get the mapped value of the specified key in uMap.
#include <iostream> #include <unordered_map> using namespace std; int main (){ unordered_map<int, string> uMap; unordered_map<int, string>::iterator it; //populating uMap uMap[101] = "John"; uMap[102] = "Marry"; uMap[103] = "Kim"; //changing the mapped value for key=103 uMap.at(103) = "Ramesh"; //accessing mapped value of specified key cout<<"uMap.at(101) = "<<uMap.at(101)<<"\n"; cout<<"uMap.at(102) = "<<uMap.at(102)<<"\n"; cout<<"uMap.at(103) = "<<uMap.at(103)<<"\n"; return 0; }
The output of the above code will be:
uMap.at(101) = John uMap.at(102) = Marry uMap.at(103) = Ramesh
❮ C++ <unordered_map> Library