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

后端 未结 8 1189
耶瑟儿~
耶瑟儿~ 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:26

    I just tried this based on UncleBens and david-rodriguez-dribeas ideas.

    This seems to work (as is) with my current compiler. g++ 3.2.3. Please let me know if it works on other compilers.

    #include 
    #include 
    #include 
    
    using namespace std;
    
    class Person
    {
    public:
        Person( int _age )
            :age(_age)
        {
        }
        int getAge() const { return age; }
    private:
        int age;
    };
    
    template 
    class get_lt_type
    {
        ResType (T::*getter) () const;
    public:
        get_lt_type(ResType (T::*method) () const ):getter(method) {}
        bool operator() ( const T* pT1, const T* pT2 ) const
        {
            return (pT1->*getter)() < (pT2->*getter)();
        }
    };
    
    template 
    get_lt_type get_lt( ResType (T::*getter) () const ) {
        return get_lt_type( getter );
    }
    
    int main() {
        vector people;
        people.push_back( new Person( 54 ) );
        people.push_back( new Person( 4 ) );
        people.push_back( new Person( 14 ) );
    
        sort( people.begin(), people.end(), get_lt( &Person::getAge) );
    
        for ( size_t i = 0; i < people.size(); ++i )
        {
            cout << people[i]->getAge() << endl;
        }
        // yes leaking Persons
        return 0;
    }
    

提交回复
热议问题