.at()

MamtaWardhani's avatar
Published May 16, 2025
Contribute to Docs

The .at() method is a built-in function in C++ STL std::map containers that safely accesses elements by their key. It provides direct reference access to the mapped value associated with a specific key. Unlike the subscript operator [], the .at() method performs bounds checking and throws an exception when attempting to access a non-existent key.

Maps in C++ are associative containers that store elements as key-value pairs, where each key is unique. The .at() method is particularly useful when ensuring that a key exists before accessing its value, making it ideal for situations where data integrity and exception handling are important.

Syntax

mapName.at(key)

Parameters:

  • key: The key value of the element to retrieve from the map.

Return value:

A direct reference to the mapped value associated with the specified key. If the key doesn’t exist, it throws an std::out_of_range exception.

Example 1: Basic Access Example using .at()

This example demonstrates how to use the .at() method to access elements in a map:

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// Create a map of strings to integers
map<string, int> studentScores;
// Insert some values
studentScores["Alice"] = 95;
studentScores["Bob"] = 87;
studentScores["Charlie"] = 92;
// Access values using at()
cout << "Alice's score: " << studentScores.at("Alice") << endl;
cout << "Bob's score: " << studentScores.at("Bob") << endl;
// Attempting to access a non-existent key safely
try {
cout << "David's score: " << studentScores.at("David") << endl;
} catch (const out_of_range& e) {
cout << "Exception: " << e.what() << endl;
cout << "David is not in the database." << endl;
}
return 0;
}

The output generated by the above code will be:

Alice's score: 95
Bob's score: 87
David's score: Exception: map::at
David is not in the database.

In this example, a map of student names to their scores is created. When trying to access “David” using .at(), it throws an exception because that key doesn’t exist in the map.

Example 2: Working with Const Maps

This example demonstrates how .at() can be used with constant maps, which is a significant advantage over the subscript operator:

#include <iostream>
#include <map>
#include <string>
using namespace std;
void printInventory(const map<string, int>& inventory) {
// at() works with const maps
try {
cout << "Apples in inventory: " << inventory.at("apple") << endl;
cout << "Oranges in inventory: " << inventory.at("orange") << endl;
cout << "Bananas in inventory: " << inventory.at("banana") << endl;
} catch (const out_of_range& e) {
cout << "A fruit is missing from inventory!" << endl;
}
}
int main() {
map<string, int> fruitInventory;
fruitInventory["apple"] = 150;
fruitInventory["orange"] = 75;
fruitInventory["banana"] = 120;
// Pass the map as const reference to the function
printInventory(fruitInventory);
return 0;
}

The output generated by this code will be:

Apples in inventory: 150
Oranges in inventory: 75
Bananas in inventory: 120

This example shows that .at() works with constant maps because it doesn’t modify the map structure. This is particularly useful when passing maps to functions as const references, which wouldn’t be possible with the subscript operator if element access is needed.

Codebyte Example: Comparing .at() with Subscript Operator

This example demonstrates the key differences between .at() and the subscript operator []:

Code
Output
Loading...

This example highlights a key difference: when trying to access “eggs” with .at(), it throws an exception because the key doesn’t exist. In contrast, when accessing “coffee” with [], it silently creates a new element with a default value (0 for numeric types).

Frequently Asked Questions

1. When should .at() be used instead of the subscript operator []?

The .at() method should be used when ensuring the key exists before accessing it, or when exception handling is needed if the key doesn’t exist. The operator [] is preferable when either retrieving a value or inserting a default value if the key doesn’t exist.

2. Can .at() be used with a constant map?

Yes, unlike the subscript operator, .at() can be used with constant maps because it doesn’t modify the map’s structure.

3. What is the time complexity of .at()?

The time complexity is O(log n), where n is the number of elements in the map.

4. What exception does .at() throw if the key is not found?

It throws a std::out_of_range exception.

5. Does .at() work with other container types?

Yes, .at() is also available in other STL containers like std::vector, std::array, and std::unordered_map.

All contributors

Contribute to Docs

Learn C++ on Codecademy