bool comp(const pair<int, int>& a, const pair<int,int>& b){
if (v[a.first]>v[b.first]) {
return true;
}
else if(v[a.first] == v[b.first] && a.second < b.second){
return true;
}
return false;
}
So, I was going through a code and I came across this comparator function for sorting a vector of pairs. Now, I am fairly new to C++. I tried reading on other questions as to how does this comparator work? But I am not able to understand. Why is the return type bool? And what does returning the value true means?
The function comp
returns true, when a
should be found before b
in the sorted array.
In this implementation, this is the case when either v[a.first]
is greater than v[b.first]
. When the first
members are equal and a.second
is smaller than b.second
, it also returns true.
In other words, the sorted array will be sorted to deliver values of v
in descending order. For values that are equal, the array is sorted according to the second
variable in ascending order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With