C++ Map Library - at() Function



Description

The C++ function std::map::at() returns a reference to the mapped value associated with key k.

Declaration

Following is the declaration for std::map::at() function form std::map header.

C++11

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

Parameters

k − Key value whose mapped value is accessed.

Return value

If object is constant qualified then method returns constant reference to mapped value otherwise returns non-constant reference.

Exceptions

If key is not present then method returns out_of_range exception.

Time complexity

Logarithmic i.e. log(n).

Example

The following example shows the usage of std::map::at() function.

#include <iostream>
#include <map>

using namespace std;

int main(void) {
   /* Initializer_list constructor */
   map<char, int> m = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5},
            };

   cout << "Value of key m['a'] = " << m.at('a') << endl;

   try {
      m.at('z');
   } catch(const out_of_range &e) {
      cerr << "Exception at " << e.what() << endl;
   }

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Value of key m['a'] = 1
Exception at map::at
map.htm
Advertisements