Hash Maps

c++17 containers intermediate

Related: Hash Sets

Hash maps, sometimes called dictionary or table, are known as unordered maps in C++. The C++ standard library’s implementation of hash map is called std::unordered_map. std::unordered_map makes no guarantees about the order of its keys and their order can depend on when they are inserted into the map. This means when iterating the key-value pairs of std::unordered_map we cannot know the order of iteration. This allows std::unordered_map to optimize for the usage of element insertion and search, or the finding of individual values by key, when compared to std::map.

#include <unordered_map>
#include <string>
#include <iostream>

int main() {
  std::unordered_map<int, std::string> statusMessages{
    {200, "Success"},
    {404, "This is not the page you're looking for"},
    {403, "Unauthorized"},
    {418, "I'm a teapot"},
  };
  statusMessages.insert({503, "Something went wrong"});

  std::cout << statusMessages[418] << "\n";
}
I'm a teapot

Element Lookup

There’s two methods to find an element in a std::unordered_map: the find() method and the square bracket operator([]). To learn more click here.

Storing Custom Types

std::unordered_map requires that the keys of the map are able to be compared for equality, meaning the keys should support the equality operator (==). The keys of std::unordered_map are also required to be able to be hashable meaning you need to write a specialization of std::hash for the key type. To learn more about storing custom types in std::unordered_map click here.

Another Key-Value Container

There’s another ordered key-value container in C++: std::map. While technically not a hash map, std::map is a key-value container that maintains its keys in sorted order at all times. Click here to learn more.


For more C++ By Example, click here.