17
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?

2
  • I am really sorry but v is just an array containing integer values. Sorry that I forgot to write it in the first place.
    – Elliot
    Mar 17, 2015 at 13:38
  • @0x499602D2 No. If v[a.first] == v[b.first] and a.second >= b.second your variant returns true, unlike the original.
    – chi
    Mar 17, 2015 at 14:12

2 Answers 2

23

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.

2
  • 1
    Great explanation, but why do we have to declare the arguments as const? Can't we do without it? I know that comp should not modify the array at all but cant we do without it?
    – Elliot
    Mar 17, 2015 at 14:20
  • 1
    @Elliot: While comp is still a valid and correct function without the const, it is better to use the const references in order to indicate that the function does not change their values. Mar 17, 2015 at 20:29
6

In case of sorting it is used to compare two values based on the result of which we can sort the array.More precisely-

Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.

The function shall not modify any of its arguments. This can either be a function pointer or a function object (functors).

2
  • So, this means, that if the value returned is true, then the first value will be considered to go before the second and vice-versa if the value returned is false?
    – Elliot
    Mar 17, 2015 at 13:40
  • @Elliot.:Yes! In this case if you return true then a is before b. Mar 17, 2015 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.