C++ Unordered_map Library - at() Function



Description

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

Declaration

Following is the declaration for std::unordered_map::at() function form std::unordered_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 is thrown.

Time complexity

Constant i.e. O(1) in average case.

Linear i.e. O(n) in worst case.

Example

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

#include <iostream>
#include <unordered_map>

using namespace std;

int main(void) {
   unordered_map<char, int> um = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5}
            };

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

   try {
      um.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 um['a'] = 1
Exception at _Map_base::at
unordered_map.htm
Advertisements