<algorithm>使用对象进行矢量排序?

Sta*_*ovv 5 c++ sorting algorithm class vector

因此,在标题中的c ++文档中有一个很好的函数,可以让你对向量进行排序.我上课了Person.我有一个指向该类(vector<Person*>)对象的指针向量,我想通过不同的参数比较人,例如年龄,姓名长度等.

我已经有了返回所需变量的函数,但我不知道该怎么做.以下是c ++参考http://www.cplusplus.com/reference/algorithm/sort/中排序向量函数的链接

小智 14

这很简单:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后:

vector<student> s;
sort(s.begin(), s.end(), cmd);
Run Code Online (Sandbox Code Playgroud)

学生将按字母顺序排序.如果两名学生姓名相同,他们将使用他们的成绩订购.