Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library

The C++ map::at function is used to return a reference to the mapped value of element identified with specified key. If the specified key does not match with key of any element of the map, the function throws an out_of_range exception.

Note: The map::at function produces the same result as operator[] function, except operator[] does not throw an out_of_range exception if the specified key does not match with key of any element of the map.


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


k Specify key value of the element in the map whose mapped value is accessed.

Time Complexity

Logarithmic i.e, Θ(log(n)).


In the below example, the map::at function is used to get the mapped value of the specified key in MyMap.

#include <iostream>
#include <map>
using namespace std;
int main (){
  map<int, string> MyMap;
  map<int, string>::iterator it;

  //populating MyMap
  MyMap[101] = "John";
  MyMap[102] = "Marry";
  MyMap[103] = "Kim";

  //changing the mapped value for key=103
  MyMap.at(103) = "Ramesh";

  //accessing mapped value of specified key
  cout<<"MyMap.at(101) = "<<MyMap.at(101)<<"\n";
  cout<<"MyMap.at(102) = "<<MyMap.at(102)<<"\n";
  cout<<"MyMap.at(103) = "<<MyMap.at(103)<<"\n";

  return 0;

The output of the above code will be:

MyMap.at(101) = John
MyMap.at(102) = Marry
MyMap.at(103) = Ramesh

❮ C++ - Map