Boost logo

Boost :

From: Shankar Sai (sai.shankar_at_[hidden])
Date: 2001-02-07 23:00:42


Is there any interest in a library that would enable member variables
to be used with the STL algorithms without having to write trivial
functions? In case I'm not being clear <g>, here's an example.

Consider a GUI having a screen where there are 10 columns of data. One
requirement is that the GUI should be capable of being sorted on all 10

The data is in a struct.

struct Data
   int column1_;

   int column2_;
   /* ... elided for brevity ... */

   int column10_;


There is a vector vec holding all the records.

You need to be able to sort on any of these fields. The idea of writing
10 trivial comparision functions is not really inspiring :-)

Would there be any interest in writing functionals which would enable

  /* Sort in descending order */
  std::sort (vec.begin (),
             vec.end (),
             make_member_comparer (&Data::column1_,
                                   std::greater <int> ())) ;

  /* Sort in ascending order by default */
  std::sort (vec.begin (),
             vec.end (),
             make_member_comparer (&Data::column1_)) ;

This was inspired by a posting on news:borland.public.cppbuilder.language
on "STL sorting question,,," by Nigel Eke. Chris Uzdavinis independently
came up with the same solution there.

The code can be found below:

#include <functional>

// Templates for comparing member variables
// Default comparision: std::less

template <class T, class Member, class Comp>
struct member_comparer : public std::binary_function <T, T, bool>

  member_comparer (Member (T::*ptr), Comp const& cmp):
                ptr_ (ptr),
                cmp_ (cmp)

  bool operator () (T const& x, T const& y) const
    return cmp_ (x.*ptr_, y.*ptr_);

  Member T::*ptr_;

  Comp cmp_;

// Convenience functions for template argument deduction

template <class T, class Member>
member_comparer <T, Member, std::less <Member> >
make_member_comparer (Member T::*ptr)
  return member_comparer <T, Member, std::less <Member> > (ptr, std::less
<Member> ());

template <class T, class Member, class Comp>
member_comparer <T, Member, Comp>
make_member_comparer (Member T::*ptr, Comp const& cmp)
  return member_comparer <T, Member, Comp> (ptr, cmp);

What do you think?

Best Regards,
Sai Shankar

Boost list run by bdawes at, gregod at, cpdaniel at, john at