C++ unordered_map

Introduction

Similar to std::unordered_set, there is also an std::unordered_map, an unordered container of key-value pairs with unique keys.

This container also allows for fast insertion, searching, and removal of elements.

The container is also data is also implemented as buckets.

What element goes into what bucket depends on the element's key hash value.

To define an unordered map, we include the <unordered_map> header.

Example:

#include <iostream> 
#include <unordered_map> 

int main() /*  ww  w.ja v a2 s.c  o m*/
{ 
     std::unordered_map<char, int> myunorderedmap = { {'a', 1}, {'b', 2},  
     {'c', 5} }; 
    for (auto el : myunorderedmap) 
    { 
        std::cout << el.first << ' '<< el.second << '\n'; 
    } 
} 

Here we initialize an unordered map with key-value pairs.

In the range-based for loop, we print both the key and the value.

Map elements are pairs.

Pairs have member functions .first for accessing a key and .second for accessing a value.




PreviousNext

Related