Skip to content
Related Articles

Related Articles

map::at() in C++ STL

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 28 Sep, 2021

Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.

map::at()

at() function is used to reference the element mapped to the key value given as the parameter to the function. For example, if we have a string “hi” mapped to an integer 1, then passing the integer 1 as the parameter of at() function will return the string “hi”.

How is at() function different from operator[] 
at() function checks the range of the container, and throws an exception when we try to access an element not in the range, while operator[] does not checks the range of the container and shows an undefined behavior when an element not in the range is accessed.

Syntax : 

mapname.at(key)
Parameters :
Key value mapped to the element to be fetched.
Returns :
Direct reference to the element at the given key value.

Examples: 

Input  :  map mymap;
          mymap['a'] = 1;
          mymap.at('a');
Output :  1

Input  :  map mymap;
          mymap["abcd"] = 7;
          mymap.at("abcd");
Output :  7

Errors and Exceptions
1. If the key is not present in the map, it throws out_of_range. 
2. It has a strong no exception throw guarantee otherwise.

C++




// CPP program to illustrate
// Implementation of at() function
#include <iostream>
#include <map>
#include <string>
using namespace std;
 
int main()
{
    // map declaration
    map<string, int> mymap;
 
    // mapping strings to integers
    mymap["hi"] = 1;
    mymap["welcome"] = 2;
    mymap["thanks"] = 3;
    mymap["bye"] = 4;
 
    // printing the integer mapped
    // by string "thanks"
    cout << mymap.at("thanks");
    return 0;
}

Output:

3

Time Complexity: O(logn)

How is at() function different from operator[] 
at() function checks the range of the container, and throws an exception when we try to access an element not in the range, while operator[] does not checks the range of the container and shows an undefined behavior when an element not in the range is accessed.
 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!