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 4
10 5
18 18
20 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.