Use unordered_map with custom keys
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 you want to use an associative container with a custom type that is not sortable. For example, a vector where (0, 1) is not smaller or larger than (1, 0), it simply points in a different direction. In such cases, you 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/y coordinates for the key. We will need a few support functions for this.
- First, we'll define a structure for the coordinates:
struct Coord { Â Â Â Â int x{}; Â Â Â Â int y{}; };
This is a simple structure with two members, x and y, for the coordinates.
- Our map will use the
Coordstructure for the key, and anintfor the value:using Coordmap = unordered_map<Coord, int...