# Algorithm and sort

• 03-27-2006
grepawksed
Algorithm and sort
Hi.
I have a vector with pointers to objects (vector<X*> ) that I would like to sort.
How can I do that with the sort that is in the STL algorithm package?

vector<X*> v;
sort(v.begin(),v.end(), .....)

but I'm not sure how I write the comparison function.
How do I do that?
• 03-27-2006
laserlight
Something like this might work:
Code:

```bool compareX(const X* a, const X* b) {         return *a < *b; } // ... vector<X*> v; sort(v.begin(), v.end(), compareX);```
• 03-27-2006
hk_mp5kpdw
Assuming you've got the less-than operator (<) defined for your X objects, then it would be this...
Code:

```class my_sort { public:     inline bool operator()(const X* lhs,const X* rhs)     {         return *lhs < *rhs;     } }; ... sort(v.begin(),v.end(),my_sort());```
That should sort them in ascending order.
• 03-27-2006
grepawksed
Is it not possible to do without the extra class?
• 03-27-2006
laserlight
Quote:

Is it not possible to do without the extra class?
Yes, if you use my version, which uses a function pointer instead. A function object is better (e.g. more flexible) in some cases, especially if it inherits from std::unary_function or std::binary_function. I am not too sure of this myself, but compilers may decide to inline the comparison made via a function object, and may be less likely to do so for a function pointer.
• 03-27-2006
grepawksed
Does your version also work if the class X is abstract?

It turns out that X is abstract and that the values of two X objects are calculated by the function
Code:

```class X{   virtual int value()=0; };```
that then should be implemented in a subclass.

so your compare function should change to
return a->value() < b->value()

Will this work? I'm getting the error
passing `const X' as `this' argument of `virtual
• 03-27-2006
laserlight
If X::value() does not logically modify the state of X, then it should be a const member function.
Code:

```class X{   virtual int value() const = 0; };```
Alternatively, you can make bool operator< a friend function, and then implement the concept of "less than" as pertains to X.
• 03-27-2006
grepawksed
Ah, great, it worked. Very big thank you!
• 03-27-2006
grepawksed
Btw, can I skip the const? Even if it's better to have itperhaps.
• 03-27-2006
laserlight
Quote:

Btw, can I skip the const? Even if it's better to have itperhaps.
Yes, though I would be disturbed if the expression (a < b) modified the state of a or b.