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”.
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 behavior 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.
C++
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string, int> mymap;
mymap["hi"] = 1;
mymap["welcome"] = 2;
mymap["thanks"] = 3;
mymap["bye"] = 4;
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 behavior when an element not in the range is accessed.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
28 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...