Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass a pointer to an operator as an argument like a pointer to a function?

Tags:

c++

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?

like image 227
Jeff Sun Avatar asked May 15 '19 14:05

Jeff Sun


People also ask

Can we pass pointer as an argument to function?

Just like any other argument, pointers can also be passed to a function as an argument.

Why do we need to use a pointer to pointer as an argument of a function?

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.

How many different ways are possible to pass a pointer to a?

There are three ways to pass variables to a function – pass by value, pass by pointer and pass by reference.

What is the correct syntax to pass a function pointer as an argument?

Which of the following is a correct syntax to pass a Function Pointer as an argument? Explanation: None.


2 Answers

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{});
like image 105
Angew is no longer proud of SO Avatar answered Oct 08 '22 20:10

Angew is no longer proud of SO


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<>{});
like image 4
Moia Avatar answered Oct 08 '22 21:10

Moia