map::at function


The map::at function can access the value of the specified key of the element pair.This function resembles the operator[] function.

mapped_type& at(const key_type& k);
const mapped_type& at(const key_type& k) const;

mapped_type:The second value type in a pair element.
key_type :The first value type in a pair element.

Link:key_type and mapped_type in pair

First function
Parameters:
k – The key of the element whose value is to be accessed.

Return type
mapped& – A reference to the second value in a pair.

Second function
Parameters:
k – The key of the element whose value is to be accessed.

Return type
mapped& – A const reference to the second value in a pair.

Note if the function cannot access the value which happens when the key supplied is nonexistent it throws std::out_of_range exception.Also note this function is more secure than using the subscript ‘[]‘ to access the value of the pair,the reason is explain in the next section.

Code example

map<int,string> mp{ {2,”Two”} , { 8 ,”Eight”} , { 4 , “Four”} , { 9 , “Nine”} };

cout<< mp.at(8) << endl
<< mp.at(4);

Output

Eight
Four

The code below throws std::out_of_range exception.

cout<< mp.at(3) << endl;

A pair element with key as 3 does not exist.

Another code is given below to test the return type of the at() function.

Code example

mp.at(2)=”TWO” ;
mp.at(9)=”NINE” ;

cout<< mp.at(2) << endl
<< mp.at(9) ;

Output

TWO
NINE


 


Stop wasting time,earn money($$$) from your website-Join Now!

Why using at() is better than using ‘[]’ to access the pair value

The only advantage of using at() function is it throws an exception if the key supplied is invalid,whereas accessing using subscript ‘[]’ does not check for validity of the key.Insecure handling of the key by the subscript ‘[]’ opens to risk of getting an undefined output in our program which we do not want at all times.However,the at() function in finding the key as invalid,it signal us by throwing the exception and thus prevent us from getting any
undefined output in our program.Mind you tracking the source of undefined result can be very frustrating in a large program.

Code example

map<int,char> mIC={{ 3 , ‘#’ } , { 4 , ‘$’ } , { 9 , ‘(‘} };

cout<< mIC.at(9) << endl
<< mIC.at( 5) ;///throws exception

cout<< mIC[3] << endl
<< mIC[2] ;//undefined ouput

A small advice prefer at() function over ‘[]’ way of accessing the value.Although I am sure using ‘[]’ is a lot simpler than calling the at() function,but you must choose security over simplicity.