Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
communitycreator

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

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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;
}
An example of the unordered_map::at() function in C++

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

RELATED TAGS

c++
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring