Algorithm STL/QUIZ/5

Please Share proof of compartor function that how it works for better understanding such that we can iterate over it and can easily write our own comparator

@lakshaywadhwa001 hey,we can write our own comparator function and pass it as a third parameter in sort functiom.This “comparator” function returns a value; convertible to bool, which basically tells us whether the passed “first” argument should be placed before the passed “second” argument or not.
For eg: In the code below, suppose intervals {6,8} and {1,9} are passed as arguments in the “compareInterval” function(comparator function). Now as i1.first (=6) > i2.first (=1), so our function returns “false”, which tells us that “first” argument should not be placed before “second” argument and so sorting will be done in order like {1,9} first and then {6,8} as next.

// A C++ program to demonstrate STL sort() using
// our own comparator
#include<bits/stdc++.h>
using namespace std;

// An interval has a start time and end time
struct Interval
{
int start, end;
};

// Compares two intervals according to staring times.
bool compareInterval(Interval i1, Interval i2)
{
return (i1.start < i2.start);
}

int main()
{
Interval arr[] = { {6,8}, {1,9}, {2,4}, {4,7} };
int n = sizeof(arr)/sizeof(arr[0]);

// sort the intervals in increasing order of 
// start time 
sort(arr, arr+n, compareInterval); 

cout << "Intervals sorted by start time : \n"; 
for (int i=0; i<n; i++) 
   cout << "[" << arr[i].start << "," << arr[i].end 
        << "] "; 

return 0; 

}
Output:
Intervals sorted by start time :
[1,9] [2,4] [4,7] [6,8]

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.