map::at() in C++ STL

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.