This post will discuss how to sort a vector of custom objects in C++.

The STL library provides the std::sort algorithm defined in the <algorithm> header, which can be used to sort objects of any type. There are many ways to do it:

1. Overload T::operator<(T) function

The recommended approach is to overload the operator< for the object class. This works as operator< is the default order used by the std::sort function (std::sort it calls std::less<> which will delegate the call to the operator<).

Download  Run Code

Output:

{Abraham,Lincoln}
{Barack,Obama}
{George,Bush}
{George,Washington}
{John,Kennedy}
{John,Tyler}

2. Overload operator<(T, T) function

Instead of defining operator< (or operator>) as member functions of the class, we can also use them as free operators, as shown below:

Download  Run Code

Output:

{Abraham,Lincoln}
{Barack,Obama}
{George,Bush}
{George,Washington}
{John,Kennedy}
{John,Tyler}

3. Custom Comparator

We can also write your own comparator and pass it to the std::sort function. The comparator function decides how to order an object with respect to another object during sorting. There are many ways to write and pass the comparator function:

1. C++11 – Pass Lambda as comparison parameter to sort()

Download  Run Code

Output:

{George,Bush}
{John,Kennedy}
{Abraham,Lincoln}
{Barack,Obama}
{John,Tyler}
{George,Washington}

2. Overload bool operator()(T, T) for a custom type

Here, the idea is to pass an object of a class implementing the () operator to sort() as a comparison function.

Download  Run Code

Output:

{George,Bush}
{John,Kennedy}
{Abraham,Lincoln}
{Barack,Obama}
{John,Tyler}
{George,Washington}

3. Using binary function

Download  Run Code

Output:

{George,Bush}
{John,Kennedy}
{Abraham,Lincoln}
{Barack,Obama}
{John,Tyler}
{George,Washington}

That's all about sorting a vector of custom objects in C++.