This post will discuss how to use custom objects as keys to std::map in C++.

1. Defining less-than operator<

To use any object as a key in std::map, we have to tell the map how to compare the two objects using a comparison function in the third parameter of the std::map template. The default value of the third parameter is std::less, which delegates the comparison to operator< defined for the key type of the map.

So, we just need to define the less-than operator for the object to enable comparisons. To demonstrate, consider the following code which uses a Node object as key to std::map by defining operator<() as a member function for Node type.

Download  Run Code

Output:

{C,C11}, 2011
{C,C99}, 1999
{C++,C++14}, 2014
{C++,C++17}, 2017
{Java,Java SE 8}, 2014
{Java,Java SE 9}, 2017

 
Note that the ordered associative containers only use a strict weak order to identify their keys. Two keys x and y are equivalent if !(x < y) && !(y < x) returns true, i.e., neither x is smaller than y nor y is smaller than x. So operator< is used to detect equality, and there is no need to overload the operator==.

2. Using a comparison object

We can even avoid defining the operator< for an object type by passing a comparator function object as a third template parameter to std::map, as shown below:

Download  Run Code

Output:

{C,C99}, 1999
{C,C11}, 2011
{C++,C++17}, 2017
{C++,C++14}, 2014
{Java,Java SE 9}, 2017
{Java,Java SE 8}, 2014

3. By specializing std::less function

Instead of passing the comparator function object to std::map, we can specialize std::less in the std namespace to override the ordering.

Download  Run Code

Output:

{C,C99}, 1999
{C,C11}, 2011
{C++,C++17}, 2017
{C++,C++14}, 2014
{Java,Java SE 9}, 2017
{Java,Java SE 8}, 2014

That’s all about using custom objects as keys to std::map in C++.