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?
Just like any other argument, pointers can also be passed to a function as an argument.
You pass a pointer to pointer as argument when you want the function to set the value of the pointer. You typically do this when the function wants to allocate memory (via malloc or new) and set that value in the argument--then it will be the responsibility of the caller to free it.
There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.
Which of the following is a correct syntax to pass a Function Pointer as an argument? Explanation: None.
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{});
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<>{});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With