In this example we will discuss different ways to sort a std::list of user defined data types with custom comparators or lambda functions.

Suppose we have a type Player that contains Id and name.

It has its < operator overloaded, which compares 2 Player objects using < on its ID field.

Now lets create a list of Player objects i.e.

Now we want to sort this list of Players and we are going to use std::list::sort() for this.

std::list::sort

std::list::sort has two different overloaded versions i.e.

It uses the default sorting criteria i.e. will use < opeartor to compare the elements in list while sorting.

It accepts a Compare function or function object and use this comparator to compare the elements in list while sorting.

Lets discuss each of them,

Sorting a List with Default Criteria

To sort a std::list with default criteria i.e < operator of type, We will use version of sort() function that accepts no arguments i.e.

It will sort the list using < operator of struct Player. Thus all the players will be sorted by their ID i.e.

Now suppose we want to sort the list of Player objects using their name instead of ID. It cannot be done by using default < operator of Player in sort(). So, we will use other overloaded version of sort().

Sorting a List of Objects with Custom Comparator & Function Object

std::list::sort has an another overloaded version that accepts a function pointer as an argument and use that for comparison while sorting.

Define a comparator or function object that will compare two Player Objects using their name.

Now use the above Function object to sort the list of Player objects using name i.e.

Output:

Sorting a List of Objects with Custom Comparator & Lambda Function

We can also sort a list of Player objects by name using a Lambda function instead of defining a seperate Function object like above.

We can pass a lambda function in sort() as argument. this lambda function will compare two Player objects by name.

Now sort() will use passed lambda function to compare the Player objects while sorting.

Output:

Complete example is as follows,

 

Output:

 

To compile the above code in linux use following command,

g++ –std=c++11 example.cpp

Click Here to Subscribe for more Articles / Tutorials like this.