Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER

# Custom Comparator

Custom Comparator are used to compare the objects of user-defined classes.

Syntax:

`bool comp(object o1, object o2) {     // There can be any condition implemented as per the need of the problem statement     // For Example:    return (o1.data_member == o2.data_member); } `

The above comparator function comp() 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.

Let us take another example of using Custom Comparator for sorting.
Suppose the task is to sort an array based on its attributes value, then the idea is to create a custom comparator 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.

`bool comp(pair<int, int> a, pair<int, int> b) {     // Compare on basis of roll number     if (a.second < b.second) {         return true;     }     return false; }int main(){    vector<pair<int, int> > A;    A.push_back(make_pair(10, 5));    A.push_back(make_pair(20, 25));    A.push_back(make_pair(18, 18));    A.push_back(make_pair(25, 4));    // Sort using comparator, it will sort the array in ascending order of second value    sort(A.begin(), A.end(), comp);    for(int i = 0; i < A.size(); i++){        cout<<A[i].first<<" "<<A[i].second<<endl;    }    return 0;}`

Output:

`25 410 518 1820 25`

Try the following example in the editor below.

You are given a function `sortArray` which takes an array of pairs, sort the given array in ascending order of their sum.

Hints
• Complete Solution

## Discussion

Free Mock Assessment
Fill up the details for personalised experience.
All fields are mandatory
Current Employer *
Enter company name *
Select an option *
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
*Enter the expected year of graduation if you're student
Current Employer *
Company Name *