<算法>矢量排序使用对象? [英] <algorithm> vector sort with objects?

查看:144
本文介绍了<算法>矢量排序使用对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,在头的C ++文档中有一个很好的功能,可以让您排序载体。我有一个类。我有一个指针向量的那类对象(矢量<人*> ),我要比较的人通过不同的参数,例如年龄,姓名长度等等。

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.

我已经有它返回所需的变量函数,但我不知道该怎么做。这是在C ++参考 http://www.cplusplus.com的链接排序向量函数/参考/算法/排序/

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/

推荐答案

这是如此的简单:

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;
}

然后:

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

学生将alphabatically排序。如果两个学生有同样的名字,他们会用他们的等级进行排序。

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

这篇关于&LT;算法&GT;矢量排序使用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆