Boost logo

Boost :

From: Jan Langer (jan_at_[hidden])
Date: 2003-03-26 14:51:48


hi,
for several times i used a small utility class, so i thought it might be
interesting for boost too.
it takes pairs of arguments and compares them pairwise beginning with
the first one.
an example usage would be a special sorting operators:

struct position
{
        double x, y, z;
};

bool operator < (position const &p1, position const &p2)
{
        return compare (p1.x, p2.x)
                        (p1.y, p2.y)
                        (p1.z, p2.z);
}

is equal to

bool operator < (position const &p1, position const &p2)
{
        if (p1.x == p2.x)
                if (p1.y == p2.y)
                        return p1.z < p2.z;
                else
                        return p1.y < p2.y;
        else
                return p1.x < p2.x;
}

or

struct person
{
        std::string firstname, lastname;
};

bool operator < (person const &p1, person const &p2)
{
        return compare
                (p1.lastname, p2.lastname, cmp_case_insensitive)
                (p1.firstname, p2.firstname, cmp_case_insensitive);
}

where cmp_case_insensitive is a comparision function which is used
instead of operator < to compare the arguments.

the class itself is quite short:

class compare
{
     enum result { minus, zero, plus };

   public:

     compare () : v_ (zero) {}

     template <typename T>
     compare (T const &a, T const &b)
         : v_ (compare () (a, b).v_)
     {}
     template <typename T, typename Cmp>
     compare (T const &a, T const &b, Cmp cmp)
         : v_ (compare () (a, b, cmp).v_)
     {}

     template <typename T>
     compare &operator () (T const &a, T const &b)
     {
         if (v_ == zero)
         {
             if (a < b)
                 v_ = plus;
             else if (b < a)
                 v_ = minus;
             else
                 v_ = zero;
         }
         return *this;
     }
     template <typename T, typename Cmp>
     compare &operator () (T const &a, T const &b, Cmp cmp)
     {
         if (v_ == zero)
         {
             if (cmp (a, b))
                 v_ = plus;
             else if (cmp (b, a))
                 v_ = minus;
             else
                 v_ = zero;
         }
         return *this;
     }

     operator bool ()
     {
         return v_ == plus;
     }

   private:
     result v_;
};

-- 
jan langer ... jan_at_[hidden]
"pi ist genau drei"

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk