Why isn't std::greater working here?
I have two versions of the code below. The only difference is in the first I used my function
cmp()
as the third parameter of sort(). It outputs
3 2 1
In the second version, I used
greater<MyClass>
and I get this error:
'std::greater<MyClass>': illegal use of this type as an expression
I looked up std::greater:
"Function object class for greater-than inequality comparison
Binary function object class whose call returns whether the its first argument compares greater than the second (as returned by operator >)."
"The type shall support the operation (operator>)."
This was the only restriction I saw on the type.
Then I looked up std::sort. Regarding the third parameter:
"Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool."
"This can either be a function pointer or a function object."
Can someone explain why greater<MyClass> doesn't work:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
// This works with cmp()
#include<vector>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
class MyClass
{
int memb;
public:
MyClass(int x) : memb(x){}
int get_memb() const { return memb; }
bool operator > (const MyClass& b) { return memb > b.memb; }
};
bool cmp(const MyClass& a, const MyClass& b)
{
return a.get_memb() > b.get_memb();
}
ostream& operator << (ostream& os, const MyClass& inst)
{
os << inst.get_memb();
return os;
}
void display(MyClass m){cout << m << " ";}
int main()
{
int values[] = { 1, 2, 3 };
vector<MyClass> my_vect(values,values + 3);
sort(my_vect.begin(), my_vect.end(), cmp);
for_each(my_vect.begin(), my_vect.end(), display);
return 0;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
// does not work with greater<MyClass>
#include<vector>
#include<iostream>
#include<algorithm>
#include<functional>
using namespace std;
class MyClass
{
int memb;
public:
MyClass(int x) : memb(x){}
int get_memb() const { return memb; }
bool operator > (const MyClass& b) { return memb > b.memb; }
};
bool cmp(const MyClass& a, const MyClass& b)
{
return a.get_memb() > b.get_memb();
}
ostream& operator << (ostream& os, const MyClass& inst)
{
os << inst.get_memb();
return os;
}
void display(MyClass m){cout << m << " ";}
int main()
{
int values[] = { 1, 2, 3 };
vector<MyClass> my_vect(values,values + 3);
sort(my_vect.begin(), my_vect.end(), greater<MyClass>);
for_each(my_vect.begin(), my_vect.end(), display);
return 0;
}
|