unordered_map at() in C++
In C++, unordered_map at() is a library function used to find the value associated with a given key in the unordered_map container. Let's look at an example to see how to use this function.
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, string> um = {{1, "a"},
{2, "b"}, {3, "c"}};
// Finding the value associated with 2
cout << um.at(2);
return 0;
}
Output
b
Syntax of unordered_map at()
unordered_map::at() is the member function of std::unordered_map class defined inside <unordered_map> header file. So, we can use this function using (.) dot operator with any unordered_map object.
um.at(key);
Parameters
- key: Key whose associated value is to be found.
Return Value
- Returns a reference to the value associated with the given key if it is present.
- If the key is not present, throws out_of_range exception.
Examples of unordered_map at()
The following examples demonstrates the use of unordered_map at() function for different purposes and scenarios:
Find the Value Associated with Given Key
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, string> um = {{1, "One"},
{2, "Two"}, {3, "Three"}};
// Accessing value associated with 2
cout << um.at(2);
return 0;
}
Output
Key 30 with value GeeksforGeeks
Update the Value Associated with Given Key
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, string> um = {{1, "One"},
{2, "Two"}, {3, "Three"}};
// Updating value associated with key 2
um.at(2) = "Geeks";
cout << um.at(2);
return 0;
}
Output
Key 30 with value Geeks
Handle Exception if the Key Doesn't Exist
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int, string> um = {{1, "One"},
{2, "Two"}, {3, "Three"}};
try {
// Trying to access key that doesn't exist
cout << um.at(10);
}
catch (const exception &e) {
// Printing exception
cout << "Exception Occurred: " << e.what();
}
return 0;
}
Output
Exception Occurred: _Map_base::at
Difference between unordered_map at() and [] Operator
Both unordered_map at() and unordered_map operator [] can be used to access or update the value of a key in an unordered_map but differs in the way how they work. The following table shows primary differences between these methods:
unordered_map at() | unordered_map operator [] |
|---|---|
It is primarily used for accessing the existing key. | It is used for accessing the existing key and as well as creating the new key. |
If the key is absent, it throws std::out_of_range exception. | If the key is absent, it inserts the new key with their default value. |
Syntax: um.at(key); | Syntax: um[key]; |