Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator function in C++ meaning and working?

Tags:

c++

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?

like image 288
Elliot Avatar asked Mar 17 '15 13:03

Elliot


1 Answers

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.

like image 198
Danny Ruijters Avatar answered Oct 21 '22 07:10

Danny Ruijters