Open In App

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

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(log n)

How is at() function different from operator[] 

The at() function and the operator[] for std::map provide similar functionality in that they both allow you to access elements by their keys. However, there are following key differences between the two:

1. Behavior When the Key Does Not Exist

• If the key does not exist in the map, operator[] will automatically insert a new element with that key and a default-initialized mapped value into the map. This means it can potentially modify the map by adding a new key-value pair. whereas at() will throw an std::out_of_range exception because this method is strictly for accessing existing keys and does not modify the map in any way.

2. Return Type

• The operator[] returns a reference to the mapped value associated with the given key. If the key does not exist, a new element is inserted with a default-initialized value, and a reference to this value is returned whereas in case of at() if the key does not exist, an exception is thrown.

3. Usability With Const Maps

• The operator[] cannot be used with const maps because it has the potential to modify the map by adding new elements. whereas at() can be used with const maps because it does not modify the map, and only retrieves the value associated with the given key.

Article Tags :
C++