vector sort with objects?

2019-02-10 17:46发布

问题:

So, in the c++ documentation in the header there is a nice function that lets you sort vectors. I have a class Person. I have a vector of pointers to objects of that class (vector<Person*>) and I want to compare the people by different parameters, for example age, length of name and so on.

I already have functions which return the needed variables but I am not sure how to do that. Here is a link to the sort vector function in the c++ reference http://www.cplusplus.com/reference/algorithm/sort/

回答1:

That's so simple:

struct student
{
  string name;
  string grade;
};

bool cmd(const student & s1, const student & s2)
{
   if (s1.name != s2.name) return s1.name < s2.name;
   return s1.grade < s2.grade;
}

Then:

vector<student> s;
sort(s.begin(), s.end(), cmd);

Students will be sorted alphabatically. If two students have the same name, they will be ordered using their grade.



回答2:

Try to override operator like "<", ">" using the same properties of the objects. After that you can redefine some sort operation.