This post will discuss how to use std::pair as a key in a std::set in C++ with and without the comparison object.

1. Using default order

We can use std::pair as a key in std::set, which is defined in the <utility> header. The pair class couples together a pair of values of the same or different types, and the individual values can be accessed through its public members first and second.

We can use initializer list in C++11 to initialize a std::set with std::pair as the key. The idea is to use the std::make_pair() or {} to construct a pair object.

Download  Run Code

Output:

{A:0}
{A:4}
{B:3}
{B:4}
{C:1}

 
Since operator< is defined for pairs, std::set performs a lexicographical comparison on two pair objects to define an ordering, i.e., It will compare based on the first element. If the values of the first elements are equal, it will then compare based on the second element. They behave as if defined as:

2. Using comparison object

We can also pass a comparison object to std::set to override the default order. The comparison object is a binary predicate which can take two pair objects and defines the custom order by comparing the first and second element of both pairs. If the predicate returns true, the first pair appears before the second pair, and if the predicate returns false, the first pair appears after the second pair.

Download  Run Code

Output:

{A:4}
{A:0}
{B:4}
{B:3}
{C:1}

3. Specializing std::less function

If you do not want to pass the comparison object but still want to override the default order, we can do that by specializing std::less in the std namespace. This works as the default for the second template parameter of std::set is std::less, which will delegate to operator<.

Download  Run Code

Output:

{A:4}
{A:0}
{B:4}
{B:3}
{C:1}

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

 
Also See:

Use pair as a key in std::unordered_set in C++