所以,在头的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.