By Vladimir

2019-05-15 14:21:03 8 Comments

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;


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?


@Angew 2019-05-15 14:22:26

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{});

@Moia 2019-05-15 14:27:41

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; });


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<>{});

Related Questions

Sponsored Content

6 Answered Questions

[SOLVED] Typedef function pointer?

  • 2010-11-28 04:50:25
  • Jack Harvin
  • 352422 View
  • 403 Score
  • 6 Answer
  • Tags:   c++ c pointers typedef

6 Answered Questions

[SOLVED] Function passed as template argument

0 Answered Questions

passing function pointer value in main to helper functions

4 Answered Questions

6 Answered Questions

[SOLVED] C++ Conversion operator for converting to function pointer

6 Answered Questions

[SOLVED] Why is the dereference operator (*) also used to declare a pointer?

4 Answered Questions

[SOLVED] error: passing xxx as 'this' argument of xxx discards qualifiers

  • 2011-05-12 04:52:56
  • 347160 View
  • 381 Score
  • 4 Answer
  • Tags:   c++

4 Answered Questions

1 Answered Questions

[SOLVED] Member function pointer of forward declared class

3 Answered Questions

[SOLVED] Operator as function pointer

Sponsored Content