Use unordered_map with Custom Keys

Learn to use unordered_map with custom keys.

We'll cover the following

With an ordered map, the type of the key must be sortable, which means it must at least support the less-than < comparison operator. Suppose we want to use an associative container with a custom type that is not sortable. For example, a vector where (0,1)(0, 1) is not smaller or larger than (1,0)(1, 0), it simply points in a different direction. In such cases, we may still use the unordered_map type. Let's look at how to do this.

How to do it

For this recipe we'll create an unordered_map object that uses x/yx/y coordinates for the key. We will need a few support functions for this.

  • First, we'll define a structure for the coordinates:

Get hands-on with 1400+ tech skills courses.