C++/STL 是否支持按属性对对象进行排序?

2022-01-07 00:00:00 sorting attributes c++ stl

我想知道 STL 是否支持此功能:

I wonder if there is support in STL for this:

假设我有一个这样的课程:

Say I have an class like this :

class Person
{
public:
  int getAge() const;
  double getIncome() const;
  ..
  ..
};

和一个向量:

vector<Person*> people;

我想按年龄对人的向量进行排序:我知道我可以通过以下方式做到这一点:

I would like to sort the vector of people by their age: I know I can do it the following way:

class AgeCmp
{
public:
   bool operator() ( const Person* p1, const Person* p2 ) const
   {
     return p1->getAge() < p2->getAge();
   }
};
sort( people.begin(), people.end(), AgeCmp() );

有没有更简洁的方法来做到这一点?仅仅因为我想根据属性"进行排序而必须定义整个类似乎有些过分.也许是这样的?

Is there a less verbose way to do this? It seems overkill to have to define a whole class just because I want to sort based on an 'attribute'. Something like this maybe?

sort( people.begin(), people.end(), cmpfn<Person,Person::getAge>() );

推荐答案

基于成员属性进行比较的通用适配器.虽然它在第一次可重用时相当冗长.

Generic adaptor to compare based on member attributes. While it is quite more verbose the first time it is reusable.

// Generic member less than
template <typename T, typename M, typename C>
struct member_lt_type 
{
   typedef M T::* member_ptr;
   member_lt_type( member_ptr p, C c ) : ptr(p), cmp(c) {}
   bool operator()( T const & lhs, T const & rhs ) const 
   {
      return cmp( lhs.*ptr, rhs.*ptr );
   }
   member_ptr ptr;
   C cmp;
};

// dereference adaptor
template <typename T, typename C>
struct dereferrer
{
   dereferrer( C cmp ) : cmp(cmp) {}
   bool operator()( T * lhs, T * rhs ) const {
      return cmp( *lhs, *rhs );
   }
   C cmp;
};

// syntactic sugar
template <typename T, typename M>
member_lt_type<T,M, std::less<M> > member_lt( M T::*ptr ) {
   return member_lt_type<T,M, std::less<M> >(ptr, std::less<M>() );
}

template <typename T, typename M, typename C>
member_lt_type<T,M,C> member_lt( M T::*ptr, C cmp ) {
   return member_lt_type<T,M,C>( ptr, cmp );
}

template <typename T, typename C>
dereferrer<T,C> deref( C cmp ) {
   return dereferrer<T,C>( cmp );
}

// usage:    
struct test { int x; }
int main() {
   std::vector<test> v;
   std::sort( v.begin(), v.end(), member_lt( &test::x ) );
   std::sort( v.begin(), v.end(), member_lt( &test::x, std::greater<int>() ) );

   std::vector<test*> vp;
   std::sort( v.begin(), v.end(), deref<test>( member_lt( &test::x ) ) );
}

相关文章