34

I am considering the general case, the following is just a simple example encountered which is easy to handle but has evoked my thoughts.

For example, I am using the sort() function of <algorithm>. Instead of defining a function as

bool cmp (int n1, int n2)
{
    return n1 > n2;
}

and

sort (arr, arr + N, cmp);

in the main function, I am wondering whether I can pass a pointer to the operator >, just as what I do to a pointer to a function, to the sort function. If so, how do I implement it?

Jeff
  • 451
  • 3
  • 8
  • @FrançoisAndrieux Thank you but I am not just focusing on this specific case. I am considering the general situation. – Jeff May 15 '19 at 14:23
  • 3
    Related : [Is it possible to get the function pointer of a built-in standard operator?](https://stackoverflow.com/questions/17644816/is-it-possible-to-get-the-function-pointer-of-a-built-in-standard-operator). – François Andrieux May 15 '19 at 14:32

2 Answers2

43

You cannot obtain a pointer to a built-in operator. But fortunately, the standard library provides function objects for all standard operators. In your case, that object's name is std::greater:

sort (arr, arr + N, std::greater<int>{});

Since C++14, you can even omit the argument type and it will be deduced from how the object is used:

sort (arr, arr + N, std::greater<>{});

And since C++17, the empty <> can be omitted too:

sort (arr, arr + N, std::greater{});
T.C.
  • 133,968
  • 17
  • 288
  • 421
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
4

You cannot do that, but you can use a lambda directly inside the sort, or store the lambda itself in a variable if you need to pass the comparator around

sort (arr, arr + N, [](int a, int b){ return a > b; });

or

auto comp = [](int a, int b){ return a > b; };
sort (arr, arr + N, comp);

or as suggested you can use the std::greater

sort (arr, arr + N, std::greater<>{});
Moia
  • 2,216
  • 1
  • 12
  • 34