.at()
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 integersmap<string, int> studentScores;// Insert some valuesstudentScores["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 safelytry {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: 95Bob's score: 87David's score: Exception: map::atDavid 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 mapstry {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 functionprintInventory(fruitInventory);return 0;}
The output generated by this code will be:
Apples in inventory: 150Oranges in inventory: 75Bananas 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 []
:
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
.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours