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

cpp

class comparator_class < // 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);

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++

// C++ program for the Comparator Class // for implementing linear search using namespace std; // Forward Declaration of classes class student; class studentcompare; // Generic function to search for object ForwardIterator search(ForwardIterator start, ForwardIterator end, T key, studentcompare& cmp) // Iterate until start equals to end while (start != end) < // If the value with given key is // found the return that index if (cmp(*start, key)) < return start; return end; // Student Class class student < // 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 < // Comparator function bool operator()(student a, student b) const // If values are the same then // return true if (a.name == b.name) < return true ; return false ; // Driver Code // Object of class student student s1( "Raj" , 23); student s2( "Prerna" , 24); // List of students s.push_back(s1); s.push_back(s2); // Search student("Prerna", 24) student searchstudent( "Prerna" , 24); studentcompare cmp; // Print if element is found using custom search if (search(s.begin(), s.end(), searchstudent, cmp) cout << "Student found!" ; cout << "Not found" ; Output
Student found!

Explanation:

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++

// C++ program for the Comparator Class // implementing sorting using namespace std; // Student Class class student < // 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 < // 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 // Object of class student student s1( "Raj" , 23); student s2( "Prerna" , 24); student s3( "Harshit" , 21); // List of students 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() // Printing the list after sorting for ( auto stu : s) < cout << stu.name << " " ; Output
Harshit Raj Prerna

Explanation:

Like Article -->

Please Login to comment.

Similar Reads

Sort an Array of dates in ascending order using Custom Comparator

Given an array arr[] of N dates in the form of "DD-MM-YYYY", the task is to sort these dates in ascending order. Examples: Input: arr[] = < "25-08-1996", "03-08-1970", "09-04-1994" >Output: 03-08-1970 09-04-1994 25-08-1996 Input: arr[] = < "03-08-1970", "09-04-2020", "19-04-2019"">Output: 03-08-1970 19-04-2019 09-04-2020 Approach: Create a Custom

6 min read Sort and separate odd and even numbers in an Array using custom comparator

Given an array arr[], containing N elements, the task is to sort and separate odd and even numbers in an Array using a custom comparator. Example: Input: arr[] = < 5, 3, 2, 8, 7, 4, 6, 9, 1 >Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = < 12, 15, 6, 2, 7, 13, 9, 4 >Output: 2 4 6 12 7 9 13 15 Approach: As we know std::sort() is used for sorting in increa

5 min read Map and External Sorting Criteria/Comparator in C++ STL

C++ Map is another commonly used STL container, it stores elements in a mapped fashion. Each element is stored as a pair having a key value and a mapped value. No two mapped values can have the same key values which means each key is unique. By default, key values in the map are in lexicographically sorted order. The map has two parts one is a key

4 min read Count number of pairs with the given Comparator

Given an array arr[], the task is to count the number of pairs (arr[i], arr[j]) on the right of every element with any custom comparator. Comparator can be of any type, some of them are given below - arr[i] > arr[j], where i < j arr[i] < arr[j], where i 2 * arr[j], where i < j Examples: Input: arr[] = <5, 4, 3, 2, 1>, comp = arr[i] >

15+ min read Comparator in C++

In C++, a comparator is a function or a function (an object that acts like a function) that is used to compare elements. It is widely used in sorting algorithms or in data structures like std::sort or std::priority_queue to define custom sorting orders. It can be used to define specific rules for comparing elements, influencing the order in which t

10 min read Comparator function of qsort() in C

Standard C library provides qsort() that can be used for sorting an array. As the name suggests, the function uses QuickSort algorithm to sort the given array. Following is the prototype of qsort() void qsort (void* base, size_t num, size_t size, int (*comparator)(const void*,const void*));Comparator Function in qsort() The key point about qsort()

4 min read How to Initialize Multiset with Custom Comparator in C++?

In C++, a multiset container stores the data in a sorted order. By default, this order is increasing order (using < operator as comparator) but we can change this order by providing a custom comparator. In this article, we will learn how to initialize a multiset with a custom comparator function in C++. For Example, Input: 1 8 6 4 9 3 2 5 7 Outp

2 min read How to Use Custom Comparator with Set in C++?

In C++, sets are associative containers that store unique elements in some sorted order. By default, set store data in increasing order but we can change this using a custom comparator. In this article, we will learn, how to declare a set with a custom comparator in C++ STL. Example Input: Data = <1, 5, 3, 4, 2>Output: mySet = Decla

2 min read How to Sort a Vector Using a Custom Comparator in C++?

In C++, vectors are containers that store data in contiguous memory locations just like arrays. But unlike arrays vectors can change their size dynamically during the runtime. In this article, we will learn how to sort a vector using a custom comparator in C++. Example: Input:myVector = <5, 2, 8, 1, 4>Output:myVector = Sort a Vector

2 min read Custom Comparator for Multimap in C++

In C++ multimap is a container to store key-value pairs allowing duplicate keys which is not allowed in a map container. By default, the multimap container uses the less than '<' operator to compare the keys for ordering the entries but also allows the use of the custom comparator. In this article, we will learn how to use a multimap with a cust

2 min read How to Declare Comparator For Set of Pair in C++?

Prerequisites: Set in C++Pair in C++The set in STL has the property that it stores only the distinct values in the sorted order if the datatype is an integer, in lexicographically smallest to largest if the data type is a string. If the datatype is pair the set keeps the distinct pairs only with the pairs sorted on the basis of the first element of

3 min read Custom Comparator in Priority_queue in C++ STL

Prerequisites: Priority Queue in C++Heap in C++Min Heap and Max Heap Priority_queue<template datatype> is a very famous STL Container generally used when we need to use Heap Data structure. The Characteristics of the heap data structure are: O(1) or constant time retrieval of min/max in the list.O(log N) time for insertion and deletion.Syntax

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

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

3 min read Behavior of virtual function in the derived class from the base class and abstract class

In this article, we will discuss the behavior of Virtual Function in the derived class and derived class from the Abstract Base Class in C++. Consider the following program: [GFGTABS] C++ // C++ program to illustrate the concept // of Virtual Function #include <bits/stdc++.h> using namespace std; // Base Class class Base < public: // Virtual

3 min read C++ boost::dynamic_bitset Class with Examples

The boost has more than 150 libraries in it, where a couple of most frequently used libraries were already included in C++ standard library. The dynamic_bitset is a powerful library used for bit manipulation. The dynamic_bitset class is used to represent a set of bits in either 0(reset) or 1(set) form. dynamic_bitset is an improvement over bitset (

15 min read Diamond operator for Anonymous Inner Class with Examples in Java

Prerequisite: Anonymous Inner Class Diamond Operator: Diamond operator was introduced in Java 7 as a new feature.The main purpose of the diamond operator is to simplify the use of generics when creating an object. It avoids unchecked warnings in a program and makes the program more readable. The diamond operator could not be used with Anonymous inn

2 min read std::is_trivially_copy_assignable class in C++ with Examples

The std::is_trivially_copy_assignable template of C++ STL is present in the <type_traits> header file. The std::is_trivially_copy_assignable template of C++ STL is used to check whether T is trivially copy assignable type or not. It return the boolean value true if T is trivially copy assignable type, otherwise return false. Header File: #inc

2 min read std::bad_weak_ptr class in C++ with Examples

Standard C++ contains several built-in exception classes, std::bad_weak_ptr is one of them. std::bad_weak_ptr is the type of the object thrown as exceptions by the constructors of shared_ptr that take weak_ptr as the argument, when the weak_ptr refers to an already deleted object. Below is the syntax for the same: Header File: <memory> Syntax

1 min read std::bad_array_new_length class in C++ with Examples

Standard C++ contains several built-in exception classes, std::bad_array_new_length is one of them.It is an exception on bad array length and thrown if the size of array is less than zero and if the array size is greater than the limit. Below is the syntax for the same: Header File: <new> Syntax: class bad_array_new_length; Return: The std::b

2 min read std::uniform_real_ distribution class in C++ with Examples

In Probability, Uniform Distribution Function refers to the distribution in which the probabilities are defined on a continuous random variable, one which can take any value between two numbers, then the distribution is said to be a continuous probability distribution. For example, the temperature throughout a given day can be represented by a cont

3 min read How to convert a class to another class type in C++?

Pre-requisite: Type Conversion in C++, Advanced C++ | Conversion OperatorsThrough class conversion, one can assign data that belongs to a particular class type to an object that belongs to another class type. Example: Let there be two classes 'A' and 'B'. If we want to allocate the details that belong to class 'A' to an object of class 'B' then thi

5 min read Difference between Base class and Derived class in C++

Base Class: A base class is a class in Object-Oriented Programming language, from which other classes are derived. The class which inherits the base class has all members of a base class as well as can also have some additional properties. The Base class members and member functions are inherited to Object of the derived class. A base class is also

2 min read Base Class Pointer Pointing to Derived Class Object in C++

Prerequisite: Pointers in C++ A pointer is a data type that stores the address of other data types. Pointers can be used for base objects as well as objects of derived classes. A pointer to the object of the derived class and a pointer to the object of the base class are type-compatible (may be used in different ways). The pointer of Base Class poi

3 min read How to Override a Base Class Method in a Derived Class in C++?

Function overriding is a concept in object-oriented programming languages, in which a function/method of a parent class is redefined in its child class to change its behavior for the objects of the child class. In this article, we are going to learn how to override a base class function in a derived class in C++. Override Inherited Methods in C++In

2 min read How to Create a Derived Class from a Base Class in C++?

In C++, one of the fundamental concepts of Object Oriented Programming (OOPS) is inheritance, allowing users to create new classes based on existing classes. The class that inherits another class is called derived class and the class that is inherited is called base class. In this article, we will learn how to create a derived class from a base cla

2 min read wcscpy() function in C++ with Examples

The wcscpy() function is defined in cwchar.h header file. The wcscpy() function is used to copy a wide character string from source to destination. Syntax: wchar_t *wcscpy(wchar_t *dest, const wchar_t *src); Parameters: This method accepts the following two parameters: dest: specifies the pointer to the destination array. src: specifies the pointer

1 min read wcscmp() function in C++ with Examples

The wcscmp() function is defined in cwchar.h header file. The wcscmp() function is used to compares two null terminating wide string and this comparison is done lexicographically. Syntax: int wcscmp(const wchar_t* str1, const wchar_t* str2); Parameters: This method takes the following two parameters: str1: This represents the pointer to the first s

2 min read String matches() Method in Java with Examples

Variants of matches() method is used to tell more precisely not test whether the given string matches to a regular expression or not as whenever this method is called in itself as matches() or be it matches() where here we do pass two arguments that are our string and regular expression, the working and output remains same. Variants of String match

4 min read ratio_equal() in C++ with examples

The ratio_equal() is an inbuilt function in C++ STL that checks if two given ratios are equal or not. Syntax: template < class ratio1_name, class ratio2_name > ratio_equal Template Parameters: The function accepts two template parameters ratio1 and ratio2 which are to be compared. Return value: The function returns true if the ratios are equa

1 min read std::equal_to in C++ with Examples

The std::equal_to allows the equality comparison to be used as a function, which means that it can be passed as an argument to templates and functions. This is not possible with the equality operator == since operators cannot be passed as parameters.Header File: #include <functional.h> Template Class: template struct equal_to : binary_functio