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

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

    These answers are all really verbose although I love the template idea! Just use lambda functions, it makes things a lot more simple!

    You could just use this:

    sort( people.begin(), people.end(), []( Person a, Person b ){ return a.age < b.age; } );
    
    0 讨论(0)
  • 2020-11-30 05:44

    You can have just a global function, or a static function. Each of these global or static functions compare against an attribute. No need to make a class. One way to hold papeters for comparison is to use boost bind, but bind is only useful for finding all classes or comparing all classes against some bound parameter. Storing data across multiple elements is the only reason to make a functor.

    Edit: also see boost lambda functions, but they are only practical for simple functions.

    0 讨论(0)
提交回复
热议问题