Last Updated : 11 Jul, 2025
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.
C++
#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;
}
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.
Parametersum.at(key);
The following examples demonstrates the use of unordered_map at() function for different purposes and scenarios:
Find the Value Associated with Given Key C++
#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;
}
Key 30 with value GeeksforGeeksUpdate the Value Associated with Given Key C++
#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;
}
Key 30 with value GeeksHandle Exception if the Key Doesn't Exist C++
#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;
}
Exception Occurred: _Map_base::atDifference 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];
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4