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

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

    You don't need to create a class - just write a function:

    #include 
    #include 
    using namespace std;
    
    struct Person {
        int age;
        int getage() const {
            return age;
        }
    };
    
    bool cmp( const Person * a, const Person * b ) {
        return a->getage() < b->getage() ;
    }
    
    int main() {
        vector  v;
        sort( v.begin(), v.end(), cmp );
    }
    

提交回复
热议问题