This post will discuss how to use an object as a key in a std::set in C++.

1. Using an object as a key in std::set function

We can use any object as a key in std::set. To facilitate this, we just need to overload the operator< for the class, as shown below:

Download  Run Code

Output:

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

 
Notice that there is no need to overload the operator== as it is not used by std::set to detect equality. The operator< is used instead. Two elements a and b are considered equal if the expression !(a < b) && !(b < a) returns true, i.e., if two elements are both not less than the other, then they must be equal.

2. Using an object as a key in std::set with comparison object

We can avoid overloading the operator< for the class by using a comparator function object to specialize std::set, as shown below:

Download  Run Code

Output:

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

 
In this version, two elements a and b are considered equivalent if the expression (!comp(a, b) && !comp(b, a)) returns true.

3. Using an object as a key in std::set by specializing std::less function

We can still override the default order of std::set and not pass the comparator function object to it 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:0}
{A:4}
{B:3}
{B:4}
{C:1}

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