What is comparator in CPP - Strings STL video while using sort function to sort elements of string?
What is comparator?
What is sort according to lexicographically mean the term used in the video of CPP - Strings STL?
Hey @Ojhajogeshkumar
Lexicographic order is the way of ordering of words based on the alphabetical order of their component letters. It is also known as lexical order, dictionary order and alphabetical order. It is similar to the way the words are arranged in the dictionary
@Ojhajogeshkumar
Comparator is basically a function through which we tell the sort function, the way in which the elements have to be arranged.
We write our own comparator function and pass it as a third parameter. 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.
#include<bits/stdc++.h>
using namespace std;
struct Interval
{
int start, end;
};
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;
}