Can anyone explain how to use custom comparators or provide a link?
What confuses me the most is that for some comparator we write the comparator as a struct/class and overload the < operator while sometimes we just write a comparator that takes two instances returns true if first should be before second in ordering.
I'll write the following snippets. Is there any difference in those two? It is just a preference? Or both are just different ways to write? If so, which is better? Also, we can just use lambda function to do this, which is much easier but I really wanted to know how traditional comparators worked.
bool comp(int& a, int& b)
{
return freq[a] < freq[b]; // Freq is a global array.
}
To sort using above comparator we write,
vector arr = {0,5,6,1}; sort(arr.begin(), arr.end(), comp);
class comparator{
bool operator()(int& a, int& b)
{
return freq[a] < freq[b] ;
}
};
To sort using this, we write the following,
vector arr = {0,5,6,1}; sort(arr.begin(),arr.end(),comparator);
auto comp = [](int& a, int& b){ return freq[a] < freq[b] };
To sort using lambda, we write the following,
vector arr = {0,5,6,1}; sort(arr.begin(),arr.end(),comp);
Please tell me when to use what, and what the differences are. I really don't seem to understand this.