What is the unordered_map::at() function in C++?

Introduction

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.

Syntax

The syntax of the unordered_map::at() function is given below:

V at(K key);

Parameters

  • Key: The key whose mapped value we want to be retrieved.

Return value

  • Value: The reference to the mapped value of the element with the equivalent key.

Code

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;
}

Explanation

  • 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++.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources