Comparator Class in C++ with Examples

Comparator Classes are used to compare the objects of user-defined classes. In order to develop a generic function use template, and in order to make the function more generic use containers, so that comparisons between data can be made.

Syntax:

filter_none

edit
close

play_arrow

link
brightness_4
code

class comparator_class {
public:
    // Comparator function
    bool operator(object o1, object o2)
    {
  
        // There can be any condition
        // implemented as per the need
        // of the problem statement
        return (o1.data_member
                == o2.data_member);
    }
}

chevron_right


Explanation: The above comparator function operator() class take two pair of objects at a time and return true if data members of the two operators are the same. There can be any condition as per the need of the problem in the comparator function. In the above example, the function returns true if data members are the same.

Example 1:
For implementing Linear Search on the array elements, searching an integer in a given array can be implemented easily. But searching any element on user defined data type can’t be implemented easily as in case of array. In this case, the comparator class is used to implement it. Below is the program for the same:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the Comparator Class
// for implementing linear search
#include <bits/stdc++.h>
using namespace std;
  
// Generic function to search for object
template <class ForwardIterator, class T>
ForwardIterator search(
    ForwardIterator start,
    ForwardIterator end, T key)
{
    // Iterate until start equals to end
    while (start != end) {
  
        // If the value with given key is
        // found the return that index
        if (*start == key) {
            return start;
        }
        start++;
    }
    return end;
}
  
// Student Class
class student {
public:
    // To store Name and Roll Number
    string name;
    int rollnum;
  
    // Overloaded Constructor
    student(string name, int rollnum)
    {
        this->name = name;
        this->rollnum = rollnum;
    }
};
  
// Comparator Class to compare 2 objects
class studentcompare {
public:
    // Comparator function
    bool operator()(student a,
                    student b)
    {
        // If values are the same then
        // return true
        if (a.name == b.name) {
            return true;
        }
        return false;
    }
};
  
// Driver Code
int main()
{
    // Object of class student
    student s1("Raj", 23);
    student s2("Prerna", 24);
  
    // List of students
    list<student> s;
    s.push_back(s1);
    s.push_back(s2);
  
    // Search student("Prerna", 24)
    student searchstudent("Prerna", 24);
  
    studentcompare cmp;
  
    // Print if element is found
    if (cmp(s2, searchstudent)) {
        cout << "Student found!";
    }
    else {
        cout << "Not found";
    }
  
    return 0;
}

chevron_right


Output:



Student found!

Explanation:

  • In the above program, a list of student objects is made in which initially 2 student objects are inserted.
  • Now to search for a particular student a template linear search function is written which makes use of the comparator class.
  • The comparator class compares the student to be searched from the list of students on the basis of their name attribute.
  • If the name attribute of the object to be searched is equal to any of the object’s name attribute in the list then it returns true, otherwise, it returns false.

Example 2:

Let us take another example of using Comparator class for sorting, suppose the task is to sort an array of objects based on its attributes value, then the idea is to create a custom comparator class in which the function on which the sorting has to be done can be mentioned. Then, it can be passed as an argument in sort() function.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the Comparator Class
// implementing sorting
  
#include <bits/stdc++.h>
using namespace std;
  
// Student Class
class student {
public:
    // To store Name and Roll Number
    string name;
    int rollnum;
  
    // Overloaded Constructor
    student(string name, int rollnum)
    {
        this->name = name;
        this->rollnum = rollnum;
    }
};
  
// Comparator Class to compare 2 objects
class studentcompare {
public:
    // Comparator function
    bool operator()(const student& a,
                    const student& b)
    {
        // Compare on basis of roll number
        if (a.rollnum < b.rollnum) {
            return true;
        }
        return false;
    }
};
  
// Driver Code
int main()
{
    // Object of class student
    student s1("Raj", 23);
    student s2("Prerna", 24);
    student s3("Harshit", 21);
  
    // List of students
    list<student> s;
    s.push_back(s1);
    s.push_back(s2);
    s.push_back(s3);
  
    // Creating object of
    // comparator class
    studentcompare cmp;
  
    // Passing the object of
    // comparator class to sort()
    s.sort(cmp);
  
    // Printing the list after sorting
    for (auto stu : s) {
        cout << stu.name << " ";
    }
  
    return 0;
}

chevron_right


Output:

Harshit Raj Prerna

Explanation:

  • In the above program, a list of student objects is made in which initially 3 student objects are inserted.
  • Now if the list of the student has to be sorted on the basis of the student’s rollno attribute then a custom comparator class has to be passed as an argument to the sort() function.
  • In the comparator class, a predicate logic has to be mentioned which returns either true or false on the basis of which the list is sorted.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.