Boost logo

Boost Users :

From: Thorsten Ottosen (tottosen_at_[hidden])
Date: 2006-03-21 11:57:57


Sebastien Fortier wrote:

> I would like to define two different sorting predicates for a class
> but I do not understand how to do this.
>
> //meteorlogicalObj.hpp
> class meteorlogicalObj {
> public:
> meteorlogicalObj(int val, Point pt) : val_(val), pt_(pt){}
> virtual ~meteorlogicalObj() {}
>
> // how would I go about creating these sorting functions that
would work with the ptr_vector class
> bool sortOnValue(const meteorlogicalObj&, const meteorlogicalObj&);
> bool sortOnPoint(const meteorlogicalObj&, const meteorlogicalObj&);
> // ...
> private:
> int val_;
> Point pt_;
> };
>
> //meteorlogicalObj.cpp
> #include "meteorlogicalObj.h"
>
> bool meteorlogicalObj::sortOnValue(const meteorlogicalObj& metObj,
const meteorlogicalObj& other)
> {
> return (metObj.val_ < other.val_);
> }
>
>
> bool meteorlogicalObj::sortOnPoint(const meteorlogicalObj& metObj,
const meteorlogicalObj& other)
> {
> return (metObj.pt_ < other.pt_);
> }
>
> //main.cpp
> boost::ptr_vector<meteorlogicalObj> metObjVec;
>
> //... fill vector
>
> metObjVec.sort( sortOnValue() ); // this does not work, what is
missing???
> metObjVec.sort( sortOnPoint() ); // this does not work, what is
missing???
>
> I can see that I probably need the indect_fun but I do not know how
to wrap my sorting function to pass them to the sorting function

You don't need to use indirect_fun<>, the algorithms do that themselves.

What you is a functor that can be properly contructed:

struct SortOnValue
{
   typedef bool result_type;
   template< class M >
   bool operator()( const M& l, const M& r ) const
   { return l.value() < r.value(); }
};

I assume that you have added a function called value to
meteorlogicalObj. Alternatively you can make the class SortOnValue a
friend to the class.

-Thorsten


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net