Using std::greater and std::sort with objects ...

Hello,

So I am attempting to use an std::sort algorithm with a vector that has pointers to my objects. So my vector definition is like this:

 
std::vector <MyObject*> unsortedVector;


I have "less than" and a "greater than" objects defined like so:

1
2
virtual bool operator<(const MyObject& secondObject);
virtual bool operator>(const MyObject& secondObject);


And what I am trying to do is this:

 
std::sort(unsortedVector.begin(), unsortedVector.end(), std::greater<MyObject*>);


However, the error I am getting is:

 
Error: type name not allowed


What can I do to sort through the pointers to the objects in descending order?

Thank you for your time.
You need parenthesis when creating the std::greater object.

 
std::sort(unsortedVector.begin(), unsortedVector.end(), std::greater<MyObject*>());

But this will not use the operator< that you have above because the types does not match.

You need parenthesis when creating the std::greater object.

std::sort(unsortedVector.begin(), unsortedVector.end(), std::greater<MyObject*>());

But this will not use the operator< that you have above because the types does not match.


Thanks for the fast reply, so as a clarification you can use a pointer to an object or the object itself as input for the std::greater function object?
Clarification: no. See: http://www.cplusplus.com/reference/functional/greater/

Q: What is the result of:
1
2
3
4
Object * foo = ...
Object * bar = ...

bool result = (foo > bar);

A: It will not call Object::operator>

Of course you could make:
bool myfunction (Object * lhs, Object * rhs) { return (*lhs > *rhs); }
(Or same as lambda.) But then you don't need that std::greater.
Topic archived. No new replies allowed.