vector sort with objects?

2019-02-10 17:02发布

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/

2条回答
我命由我不由天
2楼-- · 2019-02-10 17:36

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.

查看更多
混吃等死
3楼-- · 2019-02-10 17:50

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

查看更多
登录 后发表回答