C++ sort lambda – C++ : How to Sort a List of Objects with Custom Comparator or Lambda Function

C++ sort lambda: In the previous article, we have discussed about Different ways to Initialize a list in C++. Let us learn how to Sort a List of Objects with Custom Comparator or Lambda Function in C++ Program.

Sorting a List of Objects with Custom Comparator or Lambda Function

Std sort lambda: In this article, we will learn different ways of sorting a std::list of user defined data types with custom comparators and lambda function.

Let we have a Student type that contains roll and name.

struct Student

{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

This student type has < operator which compares two student using < on roll field. Now, let’s create list of Student Objects,

std::list<Student> list_Students = { Student(15, "Aditya"),

                                    Student(6, "Sujeet"),

                                    Student(41, "Arhan"),

                                    Student(28, "Dipti"),

                                    Student(3, "Tamanna"),};

Now, let’s sort list of Students using std::list::sort.

std::list::sort

Custom sort c++: It has two different overloaded versions i.e.

void std::list::sort(); 
// Will use default sorting criteria and will compare using < operator
template <class Compare>
void sort (Compare comparator);
//Accepts compare function or function object and using comparator it will sort

Sorting a List with Default Criteria :

Sort a list c++: We can sort a list with default criteria i.e. < operator of type which doesn’t accept any arguments. i.e. list_Students.sort();.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct Student
{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

int main(){
    std::list<Student> list_Students = { Student(15, "Aditya"),
                                    Student(6, "Sujeet"),
                                    Student(41, "Arhan"),
                                    Student(28, "Dipti"),
                                    Student(3, "Tamanna"),};
                                    
   std::cout<<"Students in the list before sorting were : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;
    // List being sorted by default criteria
    list_Students.sort();
    std::cout<<"After sorting students based on roll : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;                                    

}
Output :

Students in the list before sorting were :

15 :: Aditya

6 :: Sujeet

41 :: Arhan

28 :: Dipti

3 :: Tamanna

After sorting students based on roll :

3 :: Tamanna

6 :: Sujeet

15 :: Aditya

28 :: Dipti

41 :: Arhan

Sorting a List of Objects with Custom Comparator & Function Object :

C++ custom sort: There is another overloaded version of std::list::sort which accepts function pointer as an argument and compare while implementing sorting i.e.

template <class Compare>

void sort (Compare studcomp);

Then we will define a function object or comparator which will compare student list based on their names.

struct StudentComp

{

// Compares 2 Students objects according to their names

bool operator ()(const Student & stud1, const Student & stud2)

{

if(stud1.name == stud2.name)

return stud1 < stud2;

return stud1.name < stud2.name;

}

};


Now the above function will try to sort the list using the names by using list_Students.sort(StudentComp());

Complete program :

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct Student
{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

struct StudentComp
{
// Compares 2 student objects based on their names
    bool operator ()(const Student & stud1, const Student & stud2)
    {
        if(stud1.name == stud2.name)
            return stud1 < stud2;
        return stud1.name < stud2.name;
    }
};


int main(){
    std::list<Student> list_Students = { Student(15, "Aditya"),
                                    Student(6, "Sujeet"),
                                    Student(41, "Arhan"),
                                    Student(28, "Dipti"),
                                    Student(3, "Tamanna"),};
                                    
   std::cout<<"Students in the list before sorting were : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;
    list_Students.sort(StudentComp());
    std::cout<<"After sorting students based on name : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;                                    

}
Output :

Students in the list before sorting were :

15 :: Aditya

6 :: Sujeet

41 :: Arhan

28 :: Dipti

3 :: Tamanna

After sorting students based on name :

15 :: Aditya

41 :: Arhan

28 :: Dipti

6 :: Sujeet

3 :: Tamanna

Sorting a List of Objects with Custom Comparator & Lambda Function :

List sort c++: Instead of defining a separate Function object we can sort the list of students by using Lambda function by passing lambda function in sort() as argument.

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct Student
{
    int roll;
    std::string name;
    Student(int studRoll, std::string studName) :
            roll(studRoll), name(studName)
    {
    }
    bool operator <(const Student & studObj) const
    {
        return roll < studObj.roll;
    }
};

struct StudentComp
{
// Compares 2 student objects based on their names
    bool operator ()(const Student & stud1, const Student & stud2)
    {
        if(stud1.name == stud2.name)
            return stud1 < stud2;
        return stud1.name < stud2.name;
    }
};


int main(){
    std::list<Student> list_Students = { Student(15, "Aditya"),
                                    Student(6, "Sujeet"),
                                    Student(41, "Arhan"),
                                    Student(28, "Dipti"),
                                    Student(3, "Tamanna"),};
                                    
   std::cout<<"Students in the list before sorting were : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;
    // Sort student list using Lambda function
    list_Students.sort([](const Student & stud1, const Student & stud2)
        {
            if(stud1.name == stud2.name)
                return stud1 < stud2;
            return stud1.name < stud2.name;
        });
    std::cout<<"After sorting students based on name : "<<std::endl;
    for(Student & stud : list_Students)
        std::cout<<stud.roll<< " :: "<<stud.name<<std::endl;                                    

}
Output :

Students in the list before sorting were :

15 :: Aditya

6 :: Sujeet

41 :: Arhan

28 :: Dipti

3 :: Tamanna

After sorting students based on name :

15 :: Aditya

41 :: Arhan

28 :: Dipti

6 :: Sujeet

3 :: Tamanna