Skip to content
Related Articles

Related Articles

Improve Article

map::at() in C++ STL

  • Difficulty Level : Medium
  • Last Updated : 19 Jan, 2018

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




// 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 behaviour when an element not in the range is accessed.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :