This post will discuss how to use std::pair as a key to std::map in C++. The std::pair in C++ binds together a pair of values of the same or different types, which can then be accessed through its first and second public members.

1. Using default order

We know that the third template parameter of std::map defaults to std::less, which will delegate to operator<. So, C++ expects operator< to be defined for the type used for map’s keys.

Since the operator< is already defined for pairs, we can initialize a std::map with std::pair as the key.

Download  Run Code

Output:

{C,C11}, 2011
{C++,C++14}, 2014
{C++,C++17}, 2017
{Java,Java 7}, 2011
{Java,Java 8}, 2014

2. Using a comparison object

We can also pass a comparison object as the third template parameter to std::map to override its default order. The comparison object takes two pair objects and defines the ordering of the map’s keys by comparing the first and second elements of both pairs. If it returns true, the first pair appears before the second pair, and vice versa.

Download  Run Code

Output:

{C,C11}, 2011
{C++,C++17}, 2017
{C++,C++14}, 2014
{Java,Java 8}, 2014
{Java,Java 7}, 2011

3. Specializing std::less function

There is another way to override the default order without using the comparison object. The idea is to specialize std::less in the std namespace. This can be done, as shown below:

Download  Run Code

Output:

{Java,Java 8}, 2014
{Java,Java 7}, 2011
{C++,C++17}, 2017
{C++,C++14}, 2014
{C,C11}, 2011

That’s all about using std::pair as a key to std::map in C++.