Is there support in C++/STL for sorting objects by attribute?

后端 未结 8 1197
耶瑟儿~
耶瑟儿~ 2020-11-30 05:16

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         


        
8条回答
  •  悲哀的现实
    2020-11-30 05:38

    I see that dribeas already posted that idea, but since I already wrote it, here's how you'd write a generic comparator to use getter functions.

    #include 
    
    template 
    class CompareAttributeT: public std::binary_function
    {
        typedef ResultType (Object::*Getter)() const;
        Getter getter;
    public:
        CompareAttributeT(Getter method): getter(method) {}
        bool operator()(const Object* lhv, const Object* rhv) const
        {
            return (lhv->*getter)() < (rhv->*getter)();
        }
    };
    
    template 
    CompareAttributeT CompareAttribute(ResultType (Object::*getter)() const)
    {
        return CompareAttributeT(getter);
    }
    

    Usage:

    std::sort(people.begin(), people.end(), CompareAttribute(&Person::getAge));
    

    I think it might be a good idea to overload operator() for non-pointers, but then one couldn't typedef the argument_types by inheriting from binary_function - which is probably not a great loss, since it would hard to use it where those are needed anyway, for example, one just couldn't negate the comparison functor anyway.

提交回复
热议问题