|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-07-25 08:43:39
From: "Victor A. Wagner, Jr." <vawjr_at_[hidden]>
> I've noticed in our coding, we sometimes need a comparison operator that
> works on just a single element in a struct, instead of the "entire
> struct". If we need to sort the container using just this "key"; we, of
> course, write the comparison function/functor and then:
>
> std::sort(c.begin(), c.end(), ourfunction);
>
> I decided to write a couple templates and helper functions called (the
ones
> you'd use) less_element() and greater_element().
>
> if then we have, e.g. :
> struct person{
> std::string firstname;
> std::string lastname:
> ....other stuff
> };
>
> and a container of them, we can:
>
> std::sort(c.begin(), c.end(), less_element(firstname));
> or....
> std::sort(c.begin(), c.end(), greater_element(lastname));
The bind equivalent to less_element is
bind(less<std::string>(), bind(&person::firstname, _1),
bind(&person::firstname, _1))
which is sufficiently complex to be impractical.
You could make a helper
template<template<class> class Comparator, class R, class T>
{insert return type here} element(R T::* pm)
{
return bind(Comparator<R>(), bind(pm, _1), bind(pm, _1));
}
where the return type is something incomprehensible (where's typeof when we
need it?).
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk