Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the greater functor doesn't work

Here is the code.

#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;

int main()
{
    int a = 1;
    int b=2;
    if(greater<int>(a,b))
        cout<<"YES";
    else
        cout<<"NO";
}

When I compile it, the error message is: error C2661: “std::greater<_Ty>::greater”:no overloaded function that takes two parameters. This is confusing, it should take two parameters, right?

I use greater with sort algorithm, it works perfectly fine. But I don't know how this error message in the above program comes about.

like image 944
richard.g Avatar asked Feb 13 '26 23:02

richard.g


2 Answers

It will work this way :

int a = 1;
int b=2;
greater<int> g;
if(g(a,b))
cout<<"YES";
else
cout<<"NO";
like image 171
T-D Avatar answered Feb 16 '26 12:02

T-D


std::greater's comparison functionality is done through its operator() or the function call operator. With you doing

greater<int>(a,b)

you are creating a greater<int> object and not doing a comparison. The error actually says that there is no constructor accepting two ints because you are attempting to create an object of it.

Create first a greater<int> object then use its function call operator

greater<int>()(a, b)
//          |/|----|
//          | |
//          | |- Then call greater<int>::operator() which does the comparison 
//          |- Create a temporary greater<int> object

Live example

like image 33
Mark Garcia Avatar answered Feb 16 '26 13:02

Mark Garcia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!