Open In App

How to Sort using Member Function as Comparator in C++?

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, sorting is a common operation that can be customized by providing a comparator function. When working with classes, we might need to sort objects based on their member variables. Using a member function as a comparator is a good technique to achieve this.

In this article, we will learn how to sort using a member function as a comparator in C++.

Example:

Consider an example, where we have a Student class with name and age as its attributes and we want to sort a vector of Student objects based on the age attribute.

Input:
vector<Student> students = {
Student("Alice", 23),
Student("Bob", 20),
Student("Charlie", 22)
};

Output:
Sorted students by age:
Bob 20
Charlie 22
Alice 23

Ways to Sort Using Member Function as Comparator

There are two efficient approaches to sort using a member function as a comparator in C++:

1. Sort Using a Static Member Function

In C++, the static member function is defined within the class and can be used directly as a comparator in the std::sort function. This function compares two objects of the class and determines their order based on a specific member variable, although it can access only static members of the class, but can be used as a comparator.

Example:

C++
// C++ Program to illustrate how to sort using a static
// member function

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// define a class with a compare member function
class Student {
public:
    string name;
    int age;

    // Constructor
    Student(string n, int a)
        : name(n)
        , age(a)
    {
    }

    // Static member function to compare students by age
    static bool compareByAge(const Student& a,
                             const Student& b)
    {
        return a.age < b.age;
    }
};

int main()
{
    // Initialize the vector of Student objects
    vector<Student> students
        = { Student("Alice", 23), Student("Bob", 20),
            Student("Charlie", 22) };

    // Sort the vector using the static member function as
    // the comparator
    sort(students.begin(), students.end(),
         Student::compareByAge);

    // Output the sorted list of students
    cout << "Sorted students by age:" << endl;
    for (const Student& student : students) {
        cout << student.name << " " << student.age << endl;
    }

    return 0;
}

Output
Sorted students by age:
Bob 20
Charlie 22
Alice 23

Time Complexity: O(n log n), where n is the number of elements
Auxiliary Space: O(1)

2. Sort Using a Lambda Function with Member Function Call

Another approach is to use a lambda function that can be used to call the member function as the comparator, when sorting objects. This allows more flexibility and can access non-static members.

Example:

C++
// C++ Program to illustrate how to sort using a lambda
// function calling a member function

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

// define a class student with a member function to compare
class Student {
public:
    string name;
    int age;

    // Constructor
    Student(string n, int a)
        : name(n)
        , age(a)
    {
    }

    // Member function to compare students by age
    bool isYoungerThan(const Student& other) const
    {
        return age < other.age;
    }
};

int main()
{
    // Initialize the vector of Student objects
    vector<Student> students
        = { Student("Alice", 23), Student("Bob", 20),
            Student("Charlie", 22) };

    // Sort the vector using a lambda function as the
    // comparator
    sort(students.begin(), students.end(),
         [](const Student& a, const Student& b) {
             return a.isYoungerThan(b);
         });

    // Output the sorted list of students
    cout << "Sorted students by age:" << endl;
    for (const Student& student : students) {
        cout << student.name << " " << student.age << endl;
    }

    return 0;
}

Output
Sorted students by age:
Bob 20
Charlie 22
Alice 23

Time Complexity: O(n log n), where n is the number of elements
Auxiliary Space: O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads