0

Can anyone please explain how it works?

We are not calling sortbysec as function, but still I got the right answer. Why there is no need to pass the pair in sortbysec?

Please explain, as I am confused about internal workings of std::sort function.

bool sortbysec(const pair<int, int> &a, const pair<int, int> &b)
{
    if (a.second == b.second)
        return (a.first < b.first);
    else
        return (a.second < b.second);
}

sort(v.begin(), v.end(), sortbysec);
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
TRISHA
  • 3
  • 2
  • 1
    `sortbysec` when passed as an argument into `std::sort` passes a function pointer. The `sort` function calls that function with two values from `v` any time it wants to compare `a < b`. – paddy Feb 17 '21 at 08:11
  • Okay I will read more about function pointer to know why there is no need to pass the parameters. Thanks – TRISHA Feb 17 '21 at 09:59
  • Whenever you have a function name on its own, it's a function pointer. As soon as you add some parentheses to it, it's a function _call_. These things are very different. You can pass a function around just like any other value. That's what's happening here. The function is not called when you do that. You are simply telling `std::sort` what function it can use to compare any two values. – paddy Feb 17 '21 at 10:01
  • Now got it Thanks so much @paddy :) – TRISHA Feb 18 '21 at 15:50

0 Answers0